From aaa07d6223c56e65d2fdd75ae714577c3eb11443 Mon Sep 17 00:00:00 2001 From: JSKitty Date: Tue, 5 Sep 2023 20:15:21 +0100 Subject: [PATCH] Updates --- 56.mpw.js | 2 +- 56.mpw.js.map | 2 +- index.html | 2 +- mpw.js | 2 +- mpw.js.map | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/56.mpw.js b/56.mpw.js index b2ac88de9..93a11e42e 100644 --- a/56.mpw.js +++ b/56.mpw.js @@ -1,2 +1,2 @@ -var MPW;(()=>{var e,t,r,n,a={56691:(e,t,r)=>{"use strict";var n=r(48764),a=r(17748);function o(e){return n.Buffer.from(e).toString("hex")}var s=r(27760),i=r(72697);r(2153);const c=10**8,l={current:null,main:{name:"mainnet",collateralInSats:1e12,isTestnet:!1,TICKER:"PIV",PUBKEY_PREFIX:["D"],STAKING_PREFIX:"S",PUBKEY_ADDRESS:30,SECRET_KEY:212,BIP44_TYPE:119,BIP44_TYPE_LEDGER:77,PROTOCOL_VERSION:70926,MASTERNODE_PORT:51472,Explorers:[{name:"rockdev",url:"https://explorer.rockdev.org"},{name:"zkBitcoin",url:"https://zkbitcoin.com"},{name:"Duddino",url:"https://explorer.duddino.com"}],Nodes:[{name:"Duddino",url:"https://rpc.duddino.com/mainnet"}],Consensus:{UPGRADE_V6_0:void 0},budgetCycleBlocks:43200,proposalFee:5e9,maxPaymentCycles:6,maxPayment:432e11},testnet:{name:"testnet",collateralInSats:1e12,isTestnet:!0,TICKER:"tPIV",PUBKEY_PREFIX:["x","y"],STAKING_PREFIX:"W",PUBKEY_ADDRESS:139,SECRET_KEY:239,BIP44_TYPE:1,BIP44_TYPE_LEDGER:1,PROTOCOL_VERSION:70926,MASTERNODE_PORT:51474,Explorers:[{name:"rockdev",url:"https://testnet.rockdev.org"}],Nodes:[{name:"Duddino",url:"https://rpc.duddino.com/testnet"}],Consensus:{UPGRADE_V6_0:void 0},budgetCycleBlocks:144,proposalFee:5e9,maxPaymentCycles:20,maxPayment:144e9}};l.current=l.main,r(26269);var u=r(25108);class d{cData={};strName="";strEndpoint="";async ensureCacheExists(){this.cData&&Object.keys(this.cData).length||await this.fetch()}async fetch(){try{return this.cData=await(await fetch(this.strEndpoint)).json()}catch(e){return u.warn("CoinGecko: Failed to fetch prices!"),u.warn(e),null}}}let p="usd",h=new class extends d{constructor(){super(),this.strName="CoinGecko",this.strEndpoint="https://api.coingecko.com/api/v3/coins/pivx?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false&sparkline=false"}async getPrice(e){return await this.ensureCacheExists(),this.cData?.market_data?.current_price[e]||0}async getCurrencies(){return await this.ensureCacheExists(),null==(e=this.cData)||""===e||Array.isArray(e)&&0===e.length||"object"==typeof e&&0===Object.keys(e).length?[]:Object.keys(this.cData.market_data.current_price);var e}},m=(l.current.Explorers[0],l.current.Nodes[0],2),E={hit:"A ping indicating an app load, no unique data is sent.",time_to_sync:"The time in seconds it took for MPW to last synchronise.",transaction:"A ping indicating a Tx, no unique data is sent, but may be inferred from on-chain time."};Object.keys(E);r(91555);Object.freeze({0:0,FALSE:0,PUSHDATA1:76,PUSHDATA2:77,PUSHDATA4:78,"1NEGATE":79,RESERVED:80,1:81,TRUE:81,2:82,3:83,4:84,5:85,6:86,7:87,8:88,9:89,10:90,11:91,12:92,13:93,14:94,15:95,16:96,NOP:97,VER:98,IF:99,NOTIF:100,VERIF:101,VERNOTIF:102,ELSE:103,ENDIF:104,VERIFY:105,RETURN:106,TOALTSTACK:107,FROMALTSTACK:108,"2DROP":109,"2DUP":110,"3DUP":111,"2OVER":112,"2ROT":113,"2SWAP":114,IFDUP:115,DEPTH:116,DROP:117,DUP:118,NIP:119,OVER:120,PICK:121,ROLL:122,ROT:123,SWAP:124,TUCK:125,CAT:126,SUBSTR:127,LEFT:128,RIGHT:129,SIZE:130,INVERT:131,AND:132,OR:133,XOR:134,EQUAL:135,EQUALVERIFY:136,RESERVED1:137,RESERVED2:138,"1ADD":139,"1SUB":140,"2MUL":141,"2DIV":142,NEGATE:143,ABS:144,NOT:145,"0NOTEQUAL":146,ADD:147,SUB:148,MUL:149,DIV:150,MOD:151,LSHIFT:152,RSHIFT:153,BOOLAND:154,BOOLOR:155,NUMEQUAL:156,NUMEQUALVERIFY:157,NUMNOTEQUAL:158,LESSTHAN:159,GREATERTHAN:160,LESSTHANOREQUAL:161,GREATERTHANOREQUAL:162,MIN:163,MAX:164,WITHIN:165,RIPEMD160:166,SHA1:167,SHA256:168,HASH160:169,HASH256:170,CODESEPARATOR:171,CHECKSIG:172,CHECKSIGVERIFY:173,CHECKMULTISIG:174,CHECKMULTISIGVERIFY:175,NOP1:176,NOP2:177,CHECKLOCKTIMEVERIFY:177,NOP3:178,NOP4:179,NOP5:180,NOP6:181,NOP7:182,NOP8:183,NOP9:184,NOP10:185,ZEROCOINMINT:193,ZEROCOINSPEND:194,ZEROCOINPUBLICSPEND:195,CHECKCOLDSTAKEVERIFY_LOF:209,CHECKCOLDSTAKEVERIFY:210,INVALIDOPCODE:255});var y=r(77191),T=r.n(y);r(60743),r(25108),r(3006),r(51409),r(25108),r(19755);r(25108);class f{static version=null;#e;constructor({db:e}){this.#e=e}close(){this.#e.close(),this.#e=null}async addMasternode(e,t){const r=this.#e.transaction("masternodes","readwrite").objectStore("masternodes");await r.put(e,"masternode")}async removeMasternode(e){const t=this.#e.transaction("masternodes","readwrite").objectStore("masternodes");await t.delete("masternode")}async addPromo(e){const t=this.#e.transaction("promos","readwrite").objectStore("promos");await t.put(e,e.code)}async removePromo(e){const t=this.#e.transaction("promos","readwrite").objectStore("promos");await t.delete(e)}async addAccount(e){if(!(e instanceof Account))return database_console.error("---- addAccount() called with invalid input, input dump below ----"),database_console.error(e),database_console.error("---- end of account dump ----"),createAlert("warning","Account Creation Error
Logs were dumped in your Browser Console
Please submit these privately to PIVX Labs Developers!"),!1;const t=new Account;for(const r of Object.keys(t))isSameType(e[r],t[r])?t[r]=e[r]:database_console.error('DB: addAccount() key "'+r+'" does NOT match the correct class type, likely data mismatch, please report!');const r=this.#e.transaction("accounts","readwrite").objectStore("accounts");if(await r.get("account"))return database_console.error("DB: Ran addAccount() when account already exists!");await r.put(t,"account")}async updateAccount(e,t=!1){if(!(e instanceof Account))return database_console.error("---- updateAccount() called with invalid input, input dump below ----"),database_console.error(e),database_console.error("---- end of account dump ----"),createAlert("warning","DB Update Error
Your wallet is safe, logs were dumped in your Browser Console
Please submit these privately to PIVX Labs Developers!"),!1;const r=await this.getAccount();if(!r)return database_console.error("---- updateAccount() called without an account existing, input dump below ----"),database_console.error(e),database_console.error("---- end of input dump ----"),createAlert("warning","DB Update Error
Logs were dumped in your Browser Console
Please submit these privately to PIVX Labs Developers!"),!1;for(const n of Object.keys(r))isSameType(e[n],r[n])?!t&&isEmpty(e[n])||(r[n]=e[n]):database_console.error('DB: updateAccount() key "'+n+'" does NOT match the correct class type, likely data mismatch, please report!');const n=this.#e.transaction("accounts","readwrite").objectStore("accounts");await n.put(r,"account")}async removeAccount({publicKey:e}){const t=this.#e.transaction("accounts","readwrite").objectStore("accounts");await t.delete("account")}async getAccount(){const e=this.#e.transaction("accounts","readonly").objectStore("accounts"),t=await e.get("account");if(!t)return null;const r=new Account;for(const e of Object.keys(r))isSameType(t[e],r[e])?r[e]=t[e]:database_console.error('DB: getAccount() key "'+e+'" does NOT match the correct class type, likely bad data saved, please report!');return r}async getMasternode(e){const t=this.#e.transaction("masternodes","readonly").objectStore("masternodes");return new Masternode(await t.get("masternode"))}async getAllPromos(){const e=this.#e.transaction("promos","readonly").objectStore("promos");return(await e.getAll()).map((e=>new PromoWallet(e)))}async getSettings(){const e=this.#e.transaction("settings","readonly").objectStore("settings");return new Settings(await e.get("settings"))}async setSettings(e){const t=await this.getSettings(),r=this.#e.transaction("settings","readwrite").objectStore("settings");await r.put({...t,...e},"settings")}async#t(){if(0===localStorage.length)return;const e=new Settings({analytics:localStorage.analytics,explorer:localStorage.explorer,node:localStorage.node,translation:localStorage.translation,displayCurrency:localStorage.displayCurrency});if(await this.setSettings(e),localStorage.masternode)try{const e=JSON.parse(localStorage.masternode);await this.addMasternode(e)}catch(e){database_console.error(e),createAlert("warning",ALERTS.MIGRATION_MASTERNODE_FAILURE)}if(localStorage.encwif||localStorage.publicKey)try{const e=JSON.parse(localStorage.localProposals||"[]"),t=new Account({publicKey:localStorage.publicKey,encWif:localStorage.encwif,localProposals:e});await this.addAccount(t)}catch(e){database_console.error(e),createAlert("warning",ALERTS.MIGRATION_ACCOUNT_FAILURE),localStorage.encwif&&await confirmPopup({title:translation.MIGRATION_ACCOUNT_FAILURE_TITLE,html:`${translation.MIGRATION_ACCOUNT_FAILURE_HTML} ${sanitizeHTML(localStorage.encwif)} `})}}static async create(e){const t=new f({db:null}),r=await openDB(`MPW-${e}`,2,{upgrade:(e,t)=>{database_console.log("DB: Upgrading from "+t+" to 2"),0==t&&(e.createObjectStore("masternodes"),e.createObjectStore("accounts"),e.createObjectStore("settings")),t<=1&&e.createObjectStore("promos")},blocking:()=>{t.close(),alert("New update received!"),window.location.reload()}});return t.#e=r,t}static#r=new Map;static async getInstance(){const e=cChainParams.current.name,t=this.#r.get(e);return t&&t.#e||this.#r.set(e,await f.create(e)),this.#r.get(e)}}r(25108);let g={};function O(e=32){return crypto.getRandomValues(new Uint8Array(e))}function b(e,t,r){const n=e.length;if(n-r-t.length<0){const e="CRITICAL: Overflow detected ("+(n-r-t.length)+"), possible state corruption, backup and refresh advised.";throw S("warning",e,5e3),Error(e)}let a=0;for(;r{n.style.opacity="1",n.style.zIndex="999999",n.classList.add("bounce-ani"),n.classList.add("bounce")}),100),e){case"warning":a="fa-exclamation";break;case"info":a="fa-info";break;default:a="fa-check"}n.innerHTML=`\n
\n \n
\n
\n ${t}\n
`,n.destroy=()=>{clearTimeout(n.timer),n.style.opacity="0",setTimeout((()=>{n.remove()}),600)},n.addEventListener("click",n.destroy),r>0&&(n.timer=setTimeout(n.destroy,r)),U.domAlertPos.appendChild(n)}function v(e,t=""){if("number"==typeof e&&(e=e.toString()),!e.includes("."))return e;const r=e.split("."),n=t?"font-size: "+t:"";return`${r[0]}.${r[1]}`}r(96192),r(27715),r(19755);const w=new(r(17187).EventEmitter);r(25108);var A=r(25108);class R{constructor({id:e,path:t,sats:r,script:n,vin:a=[],vout:o,height:s,status:i,isDelegate:c=!1,isReward:l=!1}={}){this.id=e,this.path=t,this.sats=r,this.script=n,this.vin=a,this.vout=o,this.height=s,this.status=i,this.isDelegate=c,this.isReward=l}equalsUTXO(e){return this.id===e.id&&this.vout===e.vout&&this.status===e.status}}class P{constructor(){this.UTXOs=[],this.subscribeToNetwork()}static CONFIRMED=0;static REMOVED=1;static PENDING=2;getUTXO(e,t){return this.UTXOs.find((r=>r.id===e&&r.vout===t))}async removeWithDelay(e,t){var r;await(r=60*e*1e3,new Promise(((e,t)=>setTimeout(e,r)))),this.removeUTXO(t)}isAlreadyStored({id:e,vout:t,status:r}){return this.UTXOs.some((n=>n.id===e&&n.vout===t&&(!r||n.status===r)))}getUTXOsByState(e){return this.UTXOs.filter((t=>t.status===e))}removeFromState(e,t){const r=this.getUTXOsByState(t);for(const t of r)if(t.id===e.id&&t.vout===e.vout){this.removeUTXO(t);break}}addUTXO({id:e,path:t,sats:r,script:n,vin:a,vout:o,height:s,status:i,isDelegate:c,isReward:l}){const u=new R({id:e,path:t,sats:r,script:n,vin:a,vout:o,height:s,status:i,isDelegate:c,isReward:l});if(this.isAlreadyStored({id:e,vout:o}))this.updateUTXO({id:e,vout:o});else{if(l&&1===a?.length){const e=this.getUTXO(a[0].txid,a[0].vout);e&&this.removeUTXO(e)}this.UTXOs.push(u)}N(!0),_(!0)}updateUTXO({id:e,vout:t}){const r=this.UTXOs.find((r=>r.id===e&&r.vout==t));r.status===P.PENDING&&(r.status=P.CONFIRMED),N(!0),_(!0)}removeUTXO(e){this.UTXOs=this.UTXOs.filter((t=>!t.equalsUTXO(e)))}autoRemoveUTXO({id:e,vout:t}){for(const r of this.UTXOs)if(r.id===e&&r.vout===t)return r.status=P.REMOVED,void this.removeWithDelay(12,r);A.error("Mempool: Failed to find UTXO "+e+" ("+t+") for auto-removal!")}autoRemoveUTXOs(e){for(const t of e)for(const e of this.UTXOs)if(e.equalsUTXO(t)){e.status=P.REMOVED,this.removeWithDelay(12,e);break}}getConfirmed(){return this.getUTXOsByState(P.CONFIRMED)}getStandardUTXOs(){return this.UTXOs.filter((e=>e.status!==P.REMOVED&&!e.isDelegate))}getDelegatedUTXOs(){return this.UTXOs.filter((e=>e.status!==P.REMOVED&&e.isDelegate))}getBalance(){return this.getStandardUTXOs().filter((e=>!function(e,t){if(t?.collateralTxId){const{collateralTxId:r,outidx:n}=t;return r===e.id&&e.vout===n}return!1}(e))).reduce(((e,t)=>e+t.sats),0)}static isValidUTXO(e){return!e.isReward||null.cachedBlockCount-e.height>100}getDelegatedBalance(){return this.getDelegatedUTXOs().reduce(((e,t)=>e+t.sats),0)}subscribeToNetwork(){w.on("utxo",(async e=>{for(const t of e)this.isAlreadyStored({id:t.txid,vout:t.vout})?this.updateUTXO({id:t.txid,vout:t.vout}):this.addUTXO(await null.getUTXOFullInfo(t))}))}}r(9424),r(25108),new TextEncoder,new TextDecoder,r(19755),r(25108);let U={};const I=new P;function D(){U.domGuiBalanceValueCurrency.innerText=p.toUpperCase(),U.domGuiStakingValueCurrency.innerText=p.toUpperCase(),U.domSendAmountValueCurrency.innerText=p.toUpperCase(),U.domSendAmountCoinsTicker.innerText=l.current.TICKER,U.domStakeAmountValueCurrency.innerText=p.toUpperCase(),U.domStakeAmountCoinsTicker.innerText=l.current.TICKER,U.domUnstakeAmountValueCurrency.innerText=p.toUpperCase(),U.domUnstakeAmountCoinsTicker.innerText=l.current.TICKER}async function C(e,t=!1){const r=await h.getPrice(p);if(r){const n=(t?_():N())/c*r,{nValue:a,cLocale:o}=function(e){let t=e;const r=Intl.supportedValuesOf("currency").includes(p.toUpperCase())?{style:"currency",currency:p,currencyDisplay:"narrowSymbol"}:{maximumFractionDigits:8,minimumFractionDigits:8};return{nValue:t,cLocale:r}}(n);e.innerText=a.toLocaleString("en-gb",o)}}function N(e=!1){const t=I.getBalance();if(e){const e=(t/c).toFixed(m),r=e.length;U.domGuiBalance.innerHTML=v(e,r>=10?"17px":"25px"),U.domAvailToDelegate.innerHTML=v(e)+" "+l.current.TICKER,D(),C(U.domGuiBalanceValue)}return t}function _(e=!1){const t=I.getDelegatedBalance();if(e){const e=(t/c).toFixed(m),r=e.length;U.domGuiBalanceStaking.innerHTML=v(e,r>=10?"17px":"25px"),U.domAvailToUndelegate.innerHTML=v(e)+" "+l.current.TICKER,D(),C(U.domGuiStakingValue,!0)}return t}function L(e){const t=`${g.unhandledException}
${function(e){const t=document.createElement("div");return t.innerText=e,t.innerHTML}(e.message||e.reason)}`;try{S("warning",t)}catch(e){alert(t)}}l.current.isTestnet;try{window.addEventListener("error",L),window.addEventListener("unhandledrejection",L)}catch(e){}function x({pkBytes:e,publicKey:t,output:r="ENCODED"}){if(!e&&!t)return null;const c="UNCOMPRESSED_HEX"!==r;let u=t?(d=t,n.Buffer.from(d,"hex")):s.$3(e,c);var d;if("UNCOMPRESSED_HEX"===r){if(65!==u.length)throw new Error("Can't uncompress an already compressed key");return o(u)}if(65===u.length&&(u=function(e){if(65!=e.length)throw new Error("Attempting to compress an invalid uncompressed key");const t=e.slice(1,33);return[e.slice(33)[31]%2==0?2:3,...t]}(u)),33!=u.length)throw new Error("Invalid public key");if("COMPRESSED_HEX"===r)return o(u);const p=(0,a.J)(new Uint8Array(u)),h=(0,i.b)(p),m=new Uint8Array(21);var E;m[0]=l.current.PUBKEY_ADDRESS,b(m,h,1);const y=(E=m,(0,a.J)((0,a.J)(new Uint8Array(E)))).slice(0,4),f=new Uint8Array(25);return b(f,m,0),b(f,y,21),T().encode(f)}r(49840),r(2099),r(27578),r(34611),r(19755),r(25108),new Map([[25870,"Open the PIVX app on your device"],[25873,"Open the PIVX app on your device"],[57408,"Navigate to the PIVX app on your device"],[27157,"Wrong app! Open the PIVX app on your device"],[27266,"Wrong app! Open the PIVX app on your device"],[27904,"Wrong app! Open the PIVX app on your device"],[27010,"Unlock your Ledger, then try again!"],[27404,"Unlock your Ledger, then try again!"]]),onmessage=function(e){for(;;){const e={};e.priv=O(),e.pub=x({pkBytes:e.priv}),postMessage(e)}}},95856:()=>{},48777:()=>{},46601:()=>{},89214:()=>{},52361:()=>{},94616:()=>{}},o={};function s(e){var t=o[e];if(void 0!==t)return t.exports;var r=o[e]={id:e,loaded:!1,exports:{}};return a[e].call(r.exports,r,r.exports,s),r.loaded=!0,r.exports}s.m=a,s.x=()=>{var e=s.O(void 0,[621,369],(()=>s(56691)));return s.O(e)},e=[],s.O=(t,r,n,a)=>{if(!r){var o=1/0;for(u=0;u=a)&&Object.keys(s.O).every((e=>s.O[e](r[c])))?r.splice(c--,1):(i=!1,a0&&e[u-1][2]>a;u--)e[u]=e[u-1];e[u]=[r,n,a]},s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,s.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var a=Object.create(null);s.r(a);var o={};t=t||[null,r({}),r([]),r(r)];for(var i=2&n&&e;"object"==typeof i&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach((t=>o[t]=()=>e[t]));return o.default=()=>e,s.d(a,o),a},s.d=(e,t)=>{for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},s.f={},s.e=e=>Promise.all(Object.keys(s.f).reduce(((t,r)=>(s.f[r](e,t),t)),[])),s.u=e=>"./"+e+".mpw.js",s.miniCssF=e=>{},s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),(()=>{var e;s.g.importScripts&&(e=s.g.location+"");var t=s.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var r=t.getElementsByTagName("script");r.length&&(e=r[r.length-1].src)}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),s.p=e})(),(()=>{s.b=self.location+"";var e={56:1};s.f.i=(t,r)=>{e[t]||importScripts(s.p+s.u(t))};var t=self.webpackChunkMPW=self.webpackChunkMPW||[],r=t.push.bind(t);t.push=t=>{var[n,a,o]=t;for(var i in a)s.o(a,i)&&(s.m[i]=a[i]);for(o&&o(s);n.length;)e[n.pop()]=1;r(t)}})(),n=s.x,s.x=()=>Promise.all([s.e(621),s.e(369)]).then(n);var i=s.x();MPW=i})(); +var MPW;(()=>{var e,t,r,n,a={56691:(e,t,r)=>{"use strict";var n=r(48764),a=r(17748);function o(e){return n.Buffer.from(e).toString("hex")}var s=r(27760),i=r(72697);r(2153);const c=10**8,l={current:null,main:{name:"mainnet",collateralInSats:1e12,isTestnet:!1,TICKER:"PIV",PUBKEY_PREFIX:["D"],STAKING_PREFIX:"S",PUBKEY_ADDRESS:30,SECRET_KEY:212,BIP44_TYPE:119,BIP44_TYPE_LEDGER:77,PROTOCOL_VERSION:70926,MASTERNODE_PORT:51472,Explorers:[{name:"rockdev",url:"https://explorer.rockdev.org"},{name:"zkBitcoin",url:"https://zkbitcoin.com"},{name:"Duddino",url:"https://explorer.duddino.com"}],Nodes:[{name:"Duddino",url:"https://rpc.duddino.com/mainnet"}],Consensus:{UPGRADE_V6_0:void 0},budgetCycleBlocks:43200,proposalFee:5e9,maxPaymentCycles:6,maxPayment:432e11},testnet:{name:"testnet",collateralInSats:1e12,isTestnet:!0,TICKER:"tPIV",PUBKEY_PREFIX:["x","y"],STAKING_PREFIX:"W",PUBKEY_ADDRESS:139,SECRET_KEY:239,BIP44_TYPE:1,BIP44_TYPE_LEDGER:1,PROTOCOL_VERSION:70926,MASTERNODE_PORT:51474,Explorers:[{name:"rockdev",url:"https://testnet.rockdev.org"}],Nodes:[{name:"Duddino",url:"https://rpc.duddino.com/testnet"}],Consensus:{UPGRADE_V6_0:void 0},budgetCycleBlocks:144,proposalFee:5e9,maxPaymentCycles:20,maxPayment:144e9}};l.current=l.main,r(26269);var u=r(25108);class d{cData={};strName="";strEndpoint="";async ensureCacheExists(){this.cData&&Object.keys(this.cData).length||await this.fetch()}async fetch(){try{return this.cData=await(await fetch(this.strEndpoint)).json()}catch(e){return u.warn("CoinGecko: Failed to fetch prices!"),u.warn(e),null}}}let p="usd",h=new class extends d{constructor(){super(),this.strName="CoinGecko",this.strEndpoint="https://api.coingecko.com/api/v3/coins/pivx?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false&sparkline=false"}async getPrice(e){return await this.ensureCacheExists(),this.cData?.market_data?.current_price[e]||0}async getCurrencies(){return await this.ensureCacheExists(),null==(e=this.cData)||""===e||Array.isArray(e)&&0===e.length||"object"==typeof e&&0===Object.keys(e).length?[]:Object.keys(this.cData.market_data.current_price);var e}},m=(l.current.Explorers[0],l.current.Nodes[0],2),E={hit:"A ping indicating an app load, no unique data is sent.",time_to_sync:"The time in seconds it took for MPW to last synchronise.",transaction:"A ping indicating a Tx, no unique data is sent, but may be inferred from on-chain time."};Object.keys(E);r(91555);Object.freeze({0:0,FALSE:0,PUSHDATA1:76,PUSHDATA2:77,PUSHDATA4:78,"1NEGATE":79,RESERVED:80,1:81,TRUE:81,2:82,3:83,4:84,5:85,6:86,7:87,8:88,9:89,10:90,11:91,12:92,13:93,14:94,15:95,16:96,NOP:97,VER:98,IF:99,NOTIF:100,VERIF:101,VERNOTIF:102,ELSE:103,ENDIF:104,VERIFY:105,RETURN:106,TOALTSTACK:107,FROMALTSTACK:108,"2DROP":109,"2DUP":110,"3DUP":111,"2OVER":112,"2ROT":113,"2SWAP":114,IFDUP:115,DEPTH:116,DROP:117,DUP:118,NIP:119,OVER:120,PICK:121,ROLL:122,ROT:123,SWAP:124,TUCK:125,CAT:126,SUBSTR:127,LEFT:128,RIGHT:129,SIZE:130,INVERT:131,AND:132,OR:133,XOR:134,EQUAL:135,EQUALVERIFY:136,RESERVED1:137,RESERVED2:138,"1ADD":139,"1SUB":140,"2MUL":141,"2DIV":142,NEGATE:143,ABS:144,NOT:145,"0NOTEQUAL":146,ADD:147,SUB:148,MUL:149,DIV:150,MOD:151,LSHIFT:152,RSHIFT:153,BOOLAND:154,BOOLOR:155,NUMEQUAL:156,NUMEQUALVERIFY:157,NUMNOTEQUAL:158,LESSTHAN:159,GREATERTHAN:160,LESSTHANOREQUAL:161,GREATERTHANOREQUAL:162,MIN:163,MAX:164,WITHIN:165,RIPEMD160:166,SHA1:167,SHA256:168,HASH160:169,HASH256:170,CODESEPARATOR:171,CHECKSIG:172,CHECKSIGVERIFY:173,CHECKMULTISIG:174,CHECKMULTISIGVERIFY:175,NOP1:176,NOP2:177,CHECKLOCKTIMEVERIFY:177,NOP3:178,NOP4:179,NOP5:180,NOP6:181,NOP7:182,NOP8:183,NOP9:184,NOP10:185,ZEROCOINMINT:193,ZEROCOINSPEND:194,ZEROCOINPUBLICSPEND:195,CHECKCOLDSTAKEVERIFY_LOF:209,CHECKCOLDSTAKEVERIFY:210,INVALIDOPCODE:255});var y=r(77191),T=r.n(y);r(60743),r(25108),r(3006),r(51409),r(25108),r(19755);r(25108);class f{static version=null;#e;constructor({db:e}){this.#e=e}close(){this.#e.close(),this.#e=null}async addMasternode(e,t){const r=this.#e.transaction("masternodes","readwrite").objectStore("masternodes");await r.put(e,"masternode")}async removeMasternode(e){const t=this.#e.transaction("masternodes","readwrite").objectStore("masternodes");await t.delete("masternode")}async addPromo(e){const t=this.#e.transaction("promos","readwrite").objectStore("promos");await t.put(e,e.code)}async removePromo(e){const t=this.#e.transaction("promos","readwrite").objectStore("promos");await t.delete(e)}async addAccount(e){if(!(e instanceof Account))return database_console.error("---- addAccount() called with invalid input, input dump below ----"),database_console.error(e),database_console.error("---- end of account dump ----"),createAlert("warning","Account Creation Error
Logs were dumped in your Browser Console
Please submit these privately to PIVX Labs Developers!"),!1;const t=new Account;for(const r of Object.keys(t))isSameType(e[r],t[r])?t[r]=e[r]:database_console.error('DB: addAccount() key "'+r+'" does NOT match the correct class type, likely data mismatch, please report!');const r=this.#e.transaction("accounts","readwrite").objectStore("accounts");if(await r.get("account"))return database_console.error("DB: Ran addAccount() when account already exists!");await r.put(t,"account")}async updateAccount(e,t=!1){if(!(e instanceof Account))return database_console.error("---- updateAccount() called with invalid input, input dump below ----"),database_console.error(e),database_console.error("---- end of account dump ----"),createAlert("warning","DB Update Error
Your wallet is safe, logs were dumped in your Browser Console
Please submit these privately to PIVX Labs Developers!"),!1;const r=await this.getAccount();if(!r)return database_console.error("---- updateAccount() called without an account existing, input dump below ----"),database_console.error(e),database_console.error("---- end of input dump ----"),createAlert("warning","DB Update Error
Logs were dumped in your Browser Console
Please submit these privately to PIVX Labs Developers!"),!1;for(const n of Object.keys(r))isSameType(e[n],r[n])?!t&&isEmpty(e[n])||(r[n]=e[n]):database_console.error('DB: updateAccount() key "'+n+'" does NOT match the correct class type, likely data mismatch, please report!');const n=this.#e.transaction("accounts","readwrite").objectStore("accounts");await n.put(r,"account")}async removeAccount({publicKey:e}){const t=this.#e.transaction("accounts","readwrite").objectStore("accounts");await t.delete("account")}async getAccount(){const e=this.#e.transaction("accounts","readonly").objectStore("accounts"),t=await e.get("account");if(!t)return null;const r=new Account;for(const e of Object.keys(r))isSameType(t[e],r[e])?r[e]=t[e]:database_console.error('DB: getAccount() key "'+e+'" does NOT match the correct class type, likely bad data saved, please report!');return r}async getMasternode(e){const t=this.#e.transaction("masternodes","readonly").objectStore("masternodes");return new Masternode(await t.get("masternode"))}async getAllPromos(){const e=this.#e.transaction("promos","readonly").objectStore("promos");return(await e.getAll()).map((e=>new PromoWallet(e)))}async getSettings(){const e=this.#e.transaction("settings","readonly").objectStore("settings");return new Settings(await e.get("settings"))}async setSettings(e){const t=await this.getSettings(),r=this.#e.transaction("settings","readwrite").objectStore("settings");await r.put({...t,...e},"settings")}async#t(){if(0===localStorage.length)return;const e=new Settings({analytics:localStorage.analytics,explorer:localStorage.explorer,node:localStorage.node,translation:localStorage.translation,displayCurrency:localStorage.displayCurrency});if(await this.setSettings(e),localStorage.masternode)try{const e=JSON.parse(localStorage.masternode);await this.addMasternode(e)}catch(e){database_console.error(e),createAlert("warning",ALERTS.MIGRATION_MASTERNODE_FAILURE)}if(localStorage.encwif||localStorage.publicKey)try{const e=JSON.parse(localStorage.localProposals||"[]"),t=new Account({publicKey:localStorage.publicKey,encWif:localStorage.encwif,localProposals:e});await this.addAccount(t)}catch(e){database_console.error(e),createAlert("warning",ALERTS.MIGRATION_ACCOUNT_FAILURE),localStorage.encwif&&await confirmPopup({title:translation.MIGRATION_ACCOUNT_FAILURE_TITLE,html:`${translation.MIGRATION_ACCOUNT_FAILURE_HTML} ${sanitizeHTML(localStorage.encwif)} `})}}static async create(e){const t=new f({db:null}),r=await openDB(`MPW-${e}`,2,{upgrade:(e,t)=>{database_console.log("DB: Upgrading from "+t+" to 2"),0==t&&(e.createObjectStore("masternodes"),e.createObjectStore("accounts"),e.createObjectStore("settings")),t<=1&&e.createObjectStore("promos")},blocking:()=>{t.close(),alert("New update received!"),window.location.reload()}});return t.#e=r,t}static#r=new Map;static async getInstance(){const e=cChainParams.current.name,t=this.#r.get(e);return t&&t.#e||this.#r.set(e,await f.create(e)),this.#r.get(e)}}r(25108);let g={};function O(e=32){return crypto.getRandomValues(new Uint8Array(e))}function b(e,t,r){const n=e.length;if(n-r-t.length<0){const e="CRITICAL: Overflow detected ("+(n-r-t.length)+"), possible state corruption, backup and refresh advised.";throw S("warning",e,5e3),Error(e)}let a=0;for(;r{n.style.opacity="1",n.style.zIndex="999999",n.classList.add("bounce-ani"),n.classList.add("bounce")}),100),e){case"warning":a="fa-exclamation";break;case"info":a="fa-info";break;default:a="fa-check"}n.innerHTML=`\n
\n \n
\n
\n ${t}\n
`,n.destroy=()=>{clearTimeout(n.timer),n.style.opacity="0",setTimeout((()=>{n.remove()}),600)},n.addEventListener("click",n.destroy),r>0&&(n.timer=setTimeout(n.destroy,r)),U.domAlertPos.appendChild(n)}function v(e,t=""){if("number"==typeof e&&(e=e.toString()),!e.includes("."))return e;const r=e.split("."),n=t?"font-size: "+t:"";return`${r[0]}.${r[1]}`}r(96192),r(27715),r(19755);const w=new(r(17187).EventEmitter);r(25108);var A=r(25108);class R{constructor({id:e,path:t,sats:r,script:n,vin:a=[],vout:o,height:s,status:i,isDelegate:c=!1,isReward:l=!1}={}){this.id=e,this.path=t,this.sats=r,this.script=n,this.vin=a,this.vout=o,this.height=s,this.status=i,this.isDelegate=c,this.isReward=l}equalsUTXO(e){return this.id===e.id&&this.vout===e.vout&&this.status===e.status}}class P{constructor(){this.UTXOs=[],this.subscribeToNetwork()}static CONFIRMED=0;static REMOVED=1;static PENDING=2;getUTXO(e,t){return this.UTXOs.find((r=>r.id===e&&r.vout===t))}async removeWithDelay(e,t){var r;await(r=60*e*1e3,new Promise(((e,t)=>setTimeout(e,r)))),this.removeUTXO(t)}isAlreadyStored({id:e,vout:t,status:r}){return this.UTXOs.some((n=>n.id===e&&n.vout===t&&(!r||n.status===r)))}getUTXOsByState(e){return this.UTXOs.filter((t=>t.status===e))}removeFromState(e,t){const r=this.getUTXOsByState(t);for(const t of r)if(t.id===e.id&&t.vout===e.vout){this.removeUTXO(t);break}}addUTXO({id:e,path:t,sats:r,script:n,vin:a,vout:o,height:s,status:i,isDelegate:c,isReward:l}){const u=new R({id:e,path:t,sats:r,script:n,vin:a,vout:o,height:s,status:i,isDelegate:c,isReward:l});if(this.isAlreadyStored({id:e,vout:o}))this.updateUTXO({id:e,vout:o});else{if(l&&1===a?.length){const e=this.getUTXO(a[0].txid,a[0].vout);e&&this.removeUTXO(e)}this.UTXOs.push(u)}N(!0),_(!0)}updateUTXO({id:e,vout:t}){const r=this.UTXOs.find((r=>r.id===e&&r.vout==t));r.status===P.PENDING&&(r.status=P.CONFIRMED),N(!0),_(!0)}removeUTXO(e){this.UTXOs=this.UTXOs.filter((t=>!t.equalsUTXO(e)))}autoRemoveUTXO({id:e,vout:t}){for(const r of this.UTXOs)if(r.id===e&&r.vout===t)return r.status=P.REMOVED,void this.removeWithDelay(12,r);A.error("Mempool: Failed to find UTXO "+e+" ("+t+") for auto-removal!")}autoRemoveUTXOs(e){for(const t of e)for(const e of this.UTXOs)if(e.equalsUTXO(t)){e.status=P.REMOVED,this.removeWithDelay(12,e);break}}getConfirmed(){return this.getUTXOsByState(P.CONFIRMED)}getStandardUTXOs(){return this.UTXOs.filter((e=>e.status!==P.REMOVED&&!e.isDelegate))}getDelegatedUTXOs(){return this.UTXOs.filter((e=>e.status!==P.REMOVED&&e.isDelegate))}getBalance(){return this.getStandardUTXOs().filter((e=>!function(e,t){if(t?.collateralTxId){const{collateralTxId:r,outidx:n}=t;return r===e.id&&e.vout===n}return!1}(e))).reduce(((e,t)=>e+t.sats),0)}static isValidUTXO(e){return!e.isReward||null.cachedBlockCount-e.height>100}getDelegatedBalance(){return this.getDelegatedUTXOs().reduce(((e,t)=>e+t.sats),0)}subscribeToNetwork(){w.on("utxo",(async e=>{for(const t of e)this.isAlreadyStored({id:t.txid,vout:t.vout})?this.updateUTXO({id:t.txid,vout:t.vout}):this.addUTXO(await null.getUTXOFullInfo(t))}))}}r(9424),r(25108),new TextEncoder,new TextDecoder,r(19755),r(25108);let U={};const I=new P;function D(){U.domGuiBalanceValueCurrency.innerText=p.toUpperCase(),U.domGuiStakingValueCurrency.innerText=p.toUpperCase(),U.domSendAmountValueCurrency.innerText=p.toUpperCase(),U.domSendAmountCoinsTicker.innerText=l.current.TICKER,U.domStakeAmountValueCurrency.innerText=p.toUpperCase(),U.domStakeAmountCoinsTicker.innerText=l.current.TICKER,U.domUnstakeAmountValueCurrency.innerText=p.toUpperCase(),U.domUnstakeAmountCoinsTicker.innerText=l.current.TICKER}async function C(e,t=!1){const r=await h.getPrice(p);if(r){const n=(t?_():N())/c*r,{nValue:a,cLocale:o}=function(e){let t=e;const r=Intl.supportedValuesOf("currency").includes(p.toUpperCase())?{style:"currency",currency:p,currencyDisplay:"narrowSymbol"}:{maximumFractionDigits:8,minimumFractionDigits:8};return{nValue:t,cLocale:r}}(n);e.innerText=a.toLocaleString("en-gb",o)}}function N(e=!1){const t=I.getBalance();if(e){const e=(t/c).toFixed(m),r=e.length;U.domGuiBalance.innerHTML=v(e,r>=10?"17px":"25px"),U.domAvailToDelegate.innerHTML=v(e)+" "+l.current.TICKER,D(),C(U.domGuiBalanceValue)}return t}function _(e=!1){const t=I.getDelegatedBalance();if(e){const e=(t/c).toFixed(m),r=e.length;U.domGuiBalanceStaking.innerHTML=v(e,r>=10?"17px":"25px"),U.domAvailToUndelegate.innerHTML=v(e)+" "+l.current.TICKER,D(),C(U.domGuiStakingValue,!0)}return t}function L(e){const t=`${g.unhandledException}
${function(e){const t=document.createElement("div");return t.innerText=e,t.innerHTML}(e.message||e.reason)}`;try{S("warning",t)}catch(e){alert(t)}}l.current.isTestnet;try{window.addEventListener("error",L),window.addEventListener("unhandledrejection",L)}catch(e){}function x({pkBytes:e,publicKey:t,output:r="ENCODED"}){if(!e&&!t)return null;const c="UNCOMPRESSED_HEX"!==r;let u=t?(d=t,n.Buffer.from(d,"hex")):s.$3(e,c);var d;if("UNCOMPRESSED_HEX"===r){if(65!==u.length)throw new Error("Can't uncompress an already compressed key");return o(u)}if(65===u.length&&(u=function(e){if(65!=e.length)throw new Error("Attempting to compress an invalid uncompressed key");const t=e.slice(1,33);return[e.slice(33)[31]%2==0?2:3,...t]}(u)),33!=u.length)throw new Error("Invalid public key");if("COMPRESSED_HEX"===r)return o(u);const p=(0,a.J)(new Uint8Array(u)),h=(0,i.b)(p),m=new Uint8Array(21);var E;m[0]=l.current.PUBKEY_ADDRESS,b(m,h,1);const y=(E=m,(0,a.J)((0,a.J)(new Uint8Array(E)))).slice(0,4),f=new Uint8Array(25);return b(f,m,0),b(f,y,21),T().encode(f)}r(49840),r(2099),r(27578),r(34611),r(25108),r(19755),new Map([[25870,"Open the PIVX app on your device"],[25873,"Open the PIVX app on your device"],[57408,"Navigate to the PIVX app on your device"],[27157,"Wrong app! Open the PIVX app on your device"],[27266,"Wrong app! Open the PIVX app on your device"],[27904,"Wrong app! Open the PIVX app on your device"],[27010,"Unlock your Ledger, then try again!"],[27404,"Unlock your Ledger, then try again!"]]),onmessage=function(e){for(;;){const e={};e.priv=O(),e.pub=x({pkBytes:e.priv}),postMessage(e)}}},95856:()=>{},48777:()=>{},46601:()=>{},89214:()=>{},52361:()=>{},94616:()=>{}},o={};function s(e){var t=o[e];if(void 0!==t)return t.exports;var r=o[e]={id:e,loaded:!1,exports:{}};return a[e].call(r.exports,r,r.exports,s),r.loaded=!0,r.exports}s.m=a,s.x=()=>{var e=s.O(void 0,[621,369],(()=>s(56691)));return s.O(e)},e=[],s.O=(t,r,n,a)=>{if(!r){var o=1/0;for(u=0;u=a)&&Object.keys(s.O).every((e=>s.O[e](r[c])))?r.splice(c--,1):(i=!1,a0&&e[u-1][2]>a;u--)e[u]=e[u-1];e[u]=[r,n,a]},s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,s.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var a=Object.create(null);s.r(a);var o={};t=t||[null,r({}),r([]),r(r)];for(var i=2&n&&e;"object"==typeof i&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach((t=>o[t]=()=>e[t]));return o.default=()=>e,s.d(a,o),a},s.d=(e,t)=>{for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},s.f={},s.e=e=>Promise.all(Object.keys(s.f).reduce(((t,r)=>(s.f[r](e,t),t)),[])),s.u=e=>"./"+e+".mpw.js",s.miniCssF=e=>{},s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),(()=>{var e;s.g.importScripts&&(e=s.g.location+"");var t=s.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var r=t.getElementsByTagName("script");r.length&&(e=r[r.length-1].src)}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),s.p=e})(),(()=>{s.b=self.location+"";var e={56:1};s.f.i=(t,r)=>{e[t]||importScripts(s.p+s.u(t))};var t=self.webpackChunkMPW=self.webpackChunkMPW||[],r=t.push.bind(t);t.push=t=>{var[n,a,o]=t;for(var i in a)s.o(a,i)&&(s.m[i]=a[i]);for(o&&o(s);n.length;)e[n.pop()]=1;r(t)}})(),n=s.x,s.x=()=>Promise.all([s.e(621),s.e(369)]).then(n);var i=s.x();MPW=i})(); //# sourceMappingURL=56.mpw.js.map \ No newline at end of file diff --git a/56.mpw.js.map b/56.mpw.js.map index 9cc0bf910..706b05393 100644 --- a/56.mpw.js.map +++ b/56.mpw.js.map @@ -1 +1 @@ -{"version":3,"file":"./56.mpw.js","mappings":"kBAAIA,ECCAC,EADAC,ECAAC,E,0DCOG,SAAS,EAAWC,GACvB,OAAO,EAAAC,OAAA,KAAYD,GAAOE,SAAS,MACvC,C,kCCNO,MAGM,EAAO,IAAM,EAab,EAAe,CACxBC,QAAS,KACTC,KAAM,CACFC,KAAM,UACNC,iBAAkB,KAClBC,WAAW,EACXC,OAAQ,MACRC,cAAe,CAAC,KAChBC,eAAgB,IAChBC,eAAgB,GAChBC,WAAY,IACZC,WAAY,IACZC,kBAAmB,GACnBC,iBAAkB,MAClBC,gBAAiB,MAEjBC,UAAW,CAEP,CAAEZ,KAAM,UAAWa,IAAK,gCACxB,CAAEb,KAAM,YAAaa,IAAK,yBAC1B,CAAEb,KAAM,UAAWa,IAAK,iCAE5BC,MAAO,CAAC,CAAEd,KAAM,UAAWa,IAAK,oCAChCE,UAAW,CAEPC,kBAAcC,GAElBC,kBAAmB,MACnBC,YAAa,IACbC,iBAAkB,EAClBC,WAAY,QAEhBC,QAAS,CACLtB,KAAM,UACNC,iBAAkB,KAClBC,WAAW,EACXC,OAAQ,OACRC,cAAe,CAAC,IAAK,KACrBC,eAAgB,IAChBC,eAAgB,IAChBC,WAAY,IACZC,WAAY,EACZC,kBAAmB,EACnBC,iBAAkB,MAClBC,gBAAiB,MAEjBC,UAAW,CAEP,CAAEZ,KAAM,UAAWa,IAAK,gCAE5BC,MAAO,CAAC,CAAEd,KAAM,UAAWa,IAAK,oCAChCE,UAAW,CAEPC,kBAAcC,GAElBC,kBAAmB,IACnBC,YAAa,IACbC,iBAAkB,GAClBC,WAAY,QAIpB,EAAavB,QAAU,EAAaC,K,wBCnE7B,MAAMwB,EAETC,MAAQ,CAAC,EAGTC,QAAU,GAGVC,YAAc,GAKdC,0BACSC,KAAKJ,OAAUK,OAAOC,KAAKF,KAAKJ,OAAOO,cAAcH,KAAKI,OACnE,CAMAL,cACI,IACI,OAAQC,KAAKJ,kBAAqBQ,MAAMJ,KAAKF,cAAcO,MAK/D,CAJE,MAAOC,GAGL,OAFAC,EAAQC,KAAK,sCACbD,EAAQC,KAAKF,GACN,IACX,CACJ,ECVG,IAKI,EAAc,MAKd,EAAU,IDMd,cAAwBX,EAC3Bc,cACIC,QACAV,KAAKH,QAAU,YACfG,KAAKF,YA5CT,yJA6CA,CAOAC,eAAeY,GAEX,aADMX,KAAKY,oBACJZ,KAAKJ,OAAOiB,aAAaC,cAAcH,IAAgB,CAClE,CAMAZ,sBAEI,aADMC,KAAKY,oBEwYJ,OAFSG,EFrYAf,KAAKJ,QEwYb,KAARmB,GACCC,MAAMC,QAAQF,IAAuB,IAAfA,EAAIZ,QACX,iBAARY,GAAgD,IAA5Bd,OAAOC,KAAKa,GAAKZ,OFxYvC,GADAF,OAAOC,KAAKF,KAAKJ,MAAMiB,YAAYC,eEoY1C,IAAiBC,CFlYpB,GCtBOG,GARY,uBAEJ,mBAMW,GA2DnB,EAAQ,CAEfC,IAAK,yDACLC,aAAc,2DACdC,YACI,2FAGiBpB,OAAOC,KAAK,G,SEyBrCD,OAAOqB,OAjJW,CAEd,EAAG,EACHC,MAAO,EACPC,UAAW,GACXC,UAAW,GACXC,UAAW,GACX,UAAW,GACXC,SAAU,GACV,EAAG,GACHC,KAAM,GACN,EAAG,GACH,EAAG,GACH,EAAG,GACH,EAAG,GACH,EAAG,GACH,EAAG,GACH,EAAG,GACH,EAAG,GACH,GAAI,GACJ,GAAI,GACJ,GAAI,GACJ,GAAI,GACJ,GAAI,GACJ,GAAI,GACJ,GAAI,GAGJC,IAAK,GACLC,IAAK,GACLC,GAAI,GACJC,MAAO,IACPC,MAAO,IACPC,SAAU,IACVC,KAAM,IACNC,MAAO,IACPC,OAAQ,IACRC,OAAQ,IAGRC,WAAY,IACZC,aAAc,IACd,QAAS,IACT,OAAQ,IACR,OAAQ,IACR,QAAS,IACT,OAAQ,IACR,QAAS,IACTC,MAAO,IACPC,MAAO,IACPC,KAAM,IACNC,IAAK,IACLC,IAAK,IACLC,KAAM,IACNC,KAAM,IACNC,KAAM,IACNC,IAAK,IACLC,KAAM,IACNC,KAAM,IAGNC,IAAK,IACLC,OAAQ,IACRC,KAAM,IACNC,MAAO,IACPC,KAAM,IAGNC,OAAQ,IACRC,IAAK,IACLC,GAAI,IACJC,IAAK,IACLC,MAAO,IACPC,YAAa,IACbC,UAAW,IACXC,UAAW,IAGX,OAAQ,IACR,OAAQ,IACR,OAAQ,IACR,OAAQ,IACRC,OAAQ,IACRC,IAAK,IACLC,IAAK,IACL,YAAa,IAEbC,IAAK,IACLC,IAAK,IACLC,IAAK,IACLC,IAAK,IACLC,IAAK,IACLC,OAAQ,IACRC,OAAQ,IAERC,QAAS,IACTC,OAAQ,IACRC,SAAU,IACVC,eAAgB,IAChBC,YAAa,IACbC,SAAU,IACVC,YAAa,IACbC,gBAAiB,IACjBC,mBAAoB,IACpBC,IAAK,IACLC,IAAK,IAELC,OAAQ,IAGRC,UAAW,IACXC,KAAM,IACNC,OAAQ,IACRC,QAAS,IACTC,QAAS,IACTC,cAAe,IACfC,SAAU,IACVC,eAAgB,IAChBC,cAAe,IACfC,oBAAqB,IAGrBC,KAAM,IACNC,KAAM,IACNC,oBAAqB,IACrBC,KAAM,IACNC,KAAM,IACNC,KAAM,IACNC,KAAM,IACNC,KAAM,IACNC,KAAM,IACNC,KAAM,IACNC,MAAO,IAGPC,aAAc,IACdC,cAAe,IACfC,oBAAqB,IAGrBC,yBAA0B,IAC1BC,qBAAsB,IAEtBC,cAAe,M,sFC1HZ,MAAM,EAMTC,eAAiB,KAKjB,GAEAzG,aAAY,GAAE0G,IACVnH,MAAK,EAAMmH,CACf,CAEAC,QACIpH,MAAK,EAAIoH,QACTpH,MAAK,EAAM,IACf,CAOAD,oBAAoBsH,EAAYC,GAC5B,MAAMC,EAAQvH,MAAK,EACdqB,YAAY,cAAe,aAC3BmG,YAAY,qBAEXD,EAAME,IAAIJ,EAAY,aAChC,CAKAtH,uBAAuBuH,GACnB,MAAMC,EAAQvH,MAAK,EACdqB,YAAY,cAAe,aAC3BmG,YAAY,qBACXD,EAAMG,OAAO,aACvB,CAMA3H,eAAe4H,GACX,MAAMJ,EAAQvH,MAAK,EACdqB,YAAY,SAAU,aACtBmG,YAAY,gBAEXD,EAAME,IAAIE,EAAOA,EAAMC,KACjC,CAKA7H,kBAAkB4H,GACd,MAAMJ,EAAQvH,MAAK,EACdqB,YAAY,SAAU,aACtBmG,YAAY,gBACXD,EAAMG,OAAOC,EACvB,CAQA5H,iBAAiB8H,GAEb,KAAMA,aAAmBC,SAUrB,OATA,iBAAQC,MACJ,sEAEJ,iBAAQA,MAAMF,GACd,iBAAQE,MAAM,iCACdC,YACI,UACA,wIAEG,EAIX,MAAMC,EAAa,IAAIH,QAKvB,IAAK,MAAMI,KAAUjI,OAAOC,KAAK+H,GAExBE,WAAWN,EAAQK,GAASD,EAAWC,IAU5CD,EAAWC,GAAUL,EAAQK,GATzB,iBAAQH,MACJ,yBACIG,EACA,iFAShB,MAAMX,EAAQvH,MAAK,EACdqB,YAAY,WAAY,aACxBmG,YAAY,YAGjB,SAAUD,EAAMa,IAAI,WAChB,OAAO,iBAAQL,MACX,2DAIFR,EAAME,IAAIQ,EAAY,UAChC,CAeAlI,oBAAoB8H,EAASQ,GAAgB,GAEzC,KAAMR,aAAmBC,SAUrB,OATA,iBAAQC,MACJ,yEAEJ,iBAAQA,MAAMF,GACd,iBAAQE,MAAM,iCACdC,YACI,UACA,sJAEG,EAIX,MAAMC,QAAmBjI,KAAKsI,aAI9B,IAAKL,EAUD,OATA,iBAAQF,MACJ,kFAEJ,iBAAQA,MAAMF,GACd,iBAAQE,MAAM,+BACdC,YACI,UACA,iIAEG,EAMX,IAAK,MAAME,KAAUjI,OAAOC,KAAK+H,GAExBE,WAAWN,EAAQK,GAASD,EAAWC,KAWvCG,GAAiBE,QAAQV,EAAQK,MAGtCD,EAAWC,GAAUL,EAAQK,IAbzB,iBAAQH,MACJ,4BACIG,EACA,iFAahB,MAAMX,EAAQvH,MAAK,EACdqB,YAAY,WAAY,aACxBmG,YAAY,kBAEXD,EAAME,IAAIQ,EAAY,UAChC,CAOAlI,qBAAoB,UAAEyI,IAClB,MAAMjB,EAAQvH,MAAK,EACdqB,YAAY,WAAY,aACxBmG,YAAY,kBAEXD,EAAMG,OAAO,UACvB,CAQA3H,mBACI,MAAMwH,EAAQvH,MAAK,EACdqB,YAAY,WAAY,YACxBmG,YAAY,YACXS,QAAmBV,EAAMa,IAAI,WAGnC,IAAKH,EAAY,OAAO,KAGxB,MAAMQ,EAAW,IAAIX,QACrB,IAAK,MAAMI,KAAUjI,OAAOC,KAAKuI,GAExBN,WAAWF,EAAWC,GAASO,EAASP,IAU7CO,EAASP,GAAUD,EAAWC,GAT1B,iBAAQH,MACJ,yBACIG,EACA,kFAUhB,OAAOO,CACX,CAKA1I,oBAAoBuH,GAChB,MAAMC,EAAQvH,MAAK,EACdqB,YAAY,cAAe,YAC3BmG,YAAY,eACjB,OAAO,IAAIkB,iBAAiBnB,EAAMa,IAAI,cAC1C,CAKArI,qBACI,MAAMwH,EAAQvH,MAAK,EACdqB,YAAY,SAAU,YACtBmG,YAAY,UAEjB,aAAcD,EAAMoB,UAAUC,KAAKjB,GAAU,IAAIkB,YAAYlB,IACjE,CAKA5H,oBACI,MAAMwH,EAAQvH,MAAK,EACdqB,YAAY,WAAY,YACxBmG,YAAY,YACjB,OAAO,IAAIsB,eAAevB,EAAMa,IAAI,YACxC,CAMArI,kBAAkBgJ,GACd,MAAMC,QAAoBhJ,KAAKiJ,cACzB1B,EAAQvH,MAAK,EACdqB,YAAY,WAAY,aACxBmG,YAAY,kBACXD,EAAME,IACR,IACOuB,KACAD,GAEP,WAER,CAMAhJ,UACI,GAA4B,IAAxBmJ,aAAa/I,OAAc,OAC/B,MAAM4I,EAAW,IAAID,SAAS,CAC1BK,UAAWD,aAAaC,UACxBC,SAAUF,aAAaE,SACvBC,KAAMH,aAAaG,KACnBC,YAAaJ,aAAaI,YAC1BC,gBAAiBL,aAAaK,kBAIlC,SAFMvJ,KAAKwJ,YAAYT,GAEnBG,aAAa7B,WACb,IACI,MAAMA,EAAaoC,KAAKC,MAAMR,aAAa7B,kBACrCrH,KAAK2J,cAActC,EAI7B,CAHE,MAAO/G,GACL,iBAAQyH,MAAMzH,GACd0H,YAAY,UAAW4B,OAAOC,6BAClC,CAGJ,GAAIX,aAAaY,QAAUZ,aAAaV,UACpC,IACI,MAAMuB,EAAiBN,KAAKC,MACxBR,aAAaa,gBAAkB,MAI7BtB,EAAW,IAAIX,QAAQ,CACzBU,UAAWU,aAAaV,UACxBwB,OAAQd,aAAaY,OACrBC,eAAgBA,UAId/J,KAAKiK,WAAWxB,EAc1B,CAbE,MAAOnI,GACL,iBAAQyH,MAAMzH,GACd0H,YAAY,UAAW4B,OAAOM,2BAC1BhB,aAAaY,cACPK,aAAa,CACfC,MAAOd,YAAYe,gCACnBC,KAAM,GACFhB,YAAYiB,kEACoBC,aAChCtB,aAAaY,mBAI7B,CAER,CAEA5C,oBAAoB9I,GAEhB,MAAMqM,EAAW,IAAI,EAAS,CAAEtD,GAAI,OAC9BA,QAAWuD,OAAO,OAAOtM,IAzWb,EAyWiC,CAC/CuM,QAAS,CAACxD,EAAIyD,KACV,iBAAQC,IACJ,sBAAwBD,EAAxB,SAEc,GAAdA,IACAzD,EAAG2D,kBAAkB,eACrB3D,EAAG2D,kBAAkB,YACrB3D,EAAG2D,kBAAkB,aAKrBF,GAAc,GACdzD,EAAG2D,kBAAkB,SACzB,EAEJC,SAAU,KAINN,EAASrD,QACT4D,MAAM,wBACNC,OAAOC,SAASC,QAAQ,IAOhC,OAJAV,GAAS,EAAMtD,EAIRsD,CACX,CAMAvD,SAAoB,IAAIkE,IAKxBlE,2BACI,MAAM9I,EAAOiN,aAAanN,QAAQE,KAC5BkN,EAAWtL,MAAK,EAAWoI,IAAIhK,GAKrC,OAJKkN,GAAaA,GAAS,GACvBtL,MAAK,EAAWuL,IAAInN,QAAY,EAASoN,OAAOpN,IAG7C4B,MAAK,EAAWoI,IAAIhK,EAC/B,E,SC5ZG,IAAI,EAAc,CAAC,EHKnB,SAAS,EAAYqN,EAAQ,IAChC,OAAOC,OAAOC,gBAAgB,IAAIC,WAAWH,GACjD,CAqBO,SAAS,EAAaI,EAAK9N,EAAO+N,GACrC,MAAMC,EAASF,EAAI1L,OAEnB,GAAI4L,EAASD,EAAM/N,EAAMoC,OAAS,EAAG,CACjC,MAAM6L,EACF,iCACCD,EAASD,EAAM/N,EAAMoC,QACtB,4DAEJ,MADA,EAAY,UAAW6L,EAAQ,KACzBC,MAAMD,EAChB,CACA,IAAIE,EAAI,EACR,KAAOJ,EAAMC,GAAQF,EAAIC,KAAS/N,EAAMmO,IAC5C,CAqCO,SAAS,EAAYC,EAAMC,EAASC,EAAU,GACjD,MAAMC,EAAWC,SAASC,cAAc,OAWxC,IAAIC,EACJ,OAXAH,EAASI,UAAUC,IAAI,iBACvBL,EAASI,UAAUC,IAAIR,GACvBS,YAAW,KACPN,EAASO,MAAMC,QAAU,IACzBR,EAASO,MAAME,OAAS,SACxBT,EAASI,UAAUC,IAAI,cACvBL,EAASI,UAAUC,IAAI,SAAS,GACjC,KAIKR,GACJ,IAAK,UACDM,EAAW,iBACX,MACJ,IAAK,OACDA,EAAW,UACX,MACJ,QAGIA,EAAW,WAKnBH,EAASU,UAAY,uCACWb,8BACZM,oEAGdL,gBAENE,EAASW,QAAU,KAEfC,aAAaZ,EAASa,OACtBb,EAASO,MAAMC,QAAU,IACzBF,YAAW,KACPN,EAASc,QAAQ,GAClB,IAAI,EAGXd,EAASe,iBAAiB,QAASf,EAASW,SAExCZ,EAAU,IAAGC,EAASa,MAAQP,WAAWN,EAASW,QAASZ,IAC/D,0BAA6BC,EACjC,CAwPO,SAASgB,EAAeC,EAAWC,EAAiB,IAIvD,GAHyB,iBAAdD,IAAwBA,EAAYA,EAAUtP,aAGpDsP,EAAUE,SAAS,KAAM,OAAOF,EAGrC,MAAMG,EAAcH,EAAUI,MAAM,KAG9BC,EAAcJ,EAAiB,cAAgBA,EAAiB,GACtE,MAAO,GAAGE,EAAY,iCAAiCE,OAAiBF,EAAY,WACxF,C,2BI/YA,MAAMG,EAAe,I,SAAIC,c,wBCWlB,MAAM,EAcTrN,aAAY,GACRsN,EAAE,KACFC,EAAI,KACJC,EAAI,OACJC,EAAM,IACNC,EAAM,GAAE,KACRC,EAAI,OACJC,EAAM,OACNC,EAAM,WACNC,GAAa,EAAK,SAClBC,GAAW,GACX,CAAC,GAGDxO,KAAK+N,GAAKA,EAIV/N,KAAKgO,KAAOA,EAIZhO,KAAKiO,KAAOA,EAIZjO,KAAKkO,OAASA,EAIdlO,KAAKmO,IAAMA,EAIXnO,KAAKoO,KAAOA,EAIZpO,KAAKqO,OAASA,EAIdrO,KAAKsO,OAASA,EAIdtO,KAAKuO,WAAaA,EAIlBvO,KAAKwO,SAAWA,CACpB,CAOAC,WAAWC,GACP,OACI1O,KAAK+N,KAAOW,EAAMX,IAClB/N,KAAKoO,OAASM,EAAMN,MACpBpO,KAAKsO,SAAWI,EAAMJ,MAE9B,EAIG,MAAM,EACT7N,cAKIT,KAAK2O,MAAQ,GACb3O,KAAK4O,oBACT,CAGA1H,iBAAmB,EAGnBA,eAAiB,EAGjBA,eAAiB,EAOjB2H,QAAQd,EAAIe,GACR,OAAO9O,KAAK2O,MAAMI,MACbL,GAAUA,EAAMX,KAAOA,GAAMW,EAAMN,OAASU,GAErD,CAOA/O,sBAAsBiP,EAASN,GL6V5B,IAAeO,UK5VQ,GAAVD,EAAe,IL6VxB,IAAIE,SAAQ,CAACC,EAAKC,IAAMxC,WAAWuC,EAAKF,MK5V3CjP,KAAKqP,WAAWX,EACpB,CAUAY,iBAAgB,GAAEvB,EAAE,KAAEK,EAAI,OAAEE,IACxB,OAAOtO,KAAK2O,MAAMY,MACbb,GACGA,EAAMX,KAAOA,GACbW,EAAMN,OAASA,KACbE,GAAUI,EAAMJ,SAAWA,IAEzC,CAOAkB,gBAAgBC,GACZ,OAAOzP,KAAK2O,MAAMe,QAAQhB,GAAUA,EAAMJ,SAAWmB,GACzD,CAOAE,gBAAgBC,EAAUH,GACtB,MAAMI,EAAkB7P,KAAKwP,gBAAgBC,GAE7C,IAAK,MAAMf,KAASmB,EAEhB,GAAInB,EAAMX,KAAO6B,EAAS7B,IAAMW,EAAMN,OAASwB,EAASxB,KAAM,CAE1DpO,KAAKqP,WAAWX,GAChB,KACJ,CAER,CAMAoB,SAAQ,GACJ/B,EAAE,KACFC,EAAI,KACJC,EAAI,OACJC,EAAM,IACNC,EAAG,KACHC,EAAI,OACJC,EAAM,OACNC,EAAM,WACNC,EAAU,SACVC,IAEA,MAAMuB,EAAU,IAAI,EAAK,CACrBhC,KACAC,OACAC,OACAC,SACAC,MACAC,OACAC,SACAC,SACAC,aACAC,aAGJ,GAAIxO,KAAKsP,gBAAgB,CAAEvB,KAAIK,SAC3BpO,KAAKgQ,WAAW,CAAEjC,KAAIK,aACnB,CAEH,GAAII,GAA4B,IAAhBL,GAAKhO,OAAc,CAC/B,MAAM8P,EAAcjQ,KAAK6O,QAAQV,EAAI,GAAG+B,KAAM/B,EAAI,GAAGC,MAGjD6B,GACAjQ,KAAKqP,WAAWY,EAExB,CACAjQ,KAAK2O,MAAMwB,KAAKJ,EACpB,CAGA,GAAW,GACX,GAAkB,EACtB,CASAC,YAAW,GAAEjC,EAAE,KAAEK,IAOb,MAAMM,EAAQ1O,KAAK2O,MAAMI,MACpBqB,GAASA,EAAKrC,KAAOA,GAAMqC,EAAKhC,MAAQA,IAErCM,EAAMJ,SACL,EAAQ+B,UACT3B,EAAMJ,OAAS,EAAQgC,WAG/B,GAAW,GACX,GAAkB,EACtB,CAMAjB,WAAWX,GACP1O,KAAK2O,MAAQ3O,KAAK2O,MAAMe,QAAQU,IAAUA,EAAK3B,WAAWC,IAC9D,CAQA6B,gBAAe,GAAExC,EAAE,KAAEK,IACjB,IAAK,MAAMM,KAAS1O,KAAK2O,MAErB,GAAID,EAAMX,KAAOA,GAAMW,EAAMN,OAASA,EAGlC,OAFAM,EAAMJ,OAAS,EAAQkC,aACvBxQ,KAAKyQ,gBAAgB,GAAI/B,GAIjC,EAAQ3G,MACJ,gCACIgG,EACA,KACAK,EACA,sBAEZ,CAMAsC,gBAAgBC,GACZ,IAAK,MAAMf,KAAYe,EACnB,IAAK,MAAMjC,KAAS1O,KAAK2O,MAErB,GAAID,EAAMD,WAAWmB,GAAW,CAC5BlB,EAAMJ,OAAS,EAAQkC,QACvBxQ,KAAKyQ,gBAAgB,GAAI/B,GACzB,KACJ,CAGZ,CAMAkC,eACI,OAAO5Q,KAAKwP,gBAAgB,EAAQc,UACxC,CAMAO,mBACI,OAAO7Q,KAAK2O,MAAMe,QACbhB,GAAUA,EAAMJ,SAAW,EAAQkC,UAAY9B,EAAMH,YAE9D,CAMAuC,oBACI,OAAO9Q,KAAK2O,MAAMe,QACbhB,GAAUA,EAAMJ,SAAW,EAAQkC,SAAW9B,EAAMH,YAE7D,CAMAwC,aAEI,OAAO/Q,KAAK6Q,mBACPnB,QAAQhB,ICi+Cd,SAA0BA,EAAOsC,GACpC,GAAIA,GAAaC,eAAgB,CAC7B,MAAM,eAAEA,EAAc,OAAEC,GAAWF,EACnC,OAAOC,IAAmBvC,EAAMX,IAAMW,EAAMN,OAAS8C,CACzD,CACI,OAAO,CAEf,CDx+CgC,CAAiBxC,KACpCyC,QAAO,CAACC,EAAGC,IAAMD,EAAIC,EAAEpD,MAAM,EACtC,CAOA/G,mBAAmBwH,GACf,OAAIA,EAAMF,UE0SH,KFzSiB8C,iBAAmB5C,EAAML,OAAS,GAI9D,CAMAkD,sBACI,OAAOvR,KAAK8Q,oBAAoBK,QAAO,CAACC,EAAGC,IAAMD,EAAIC,EAAEpD,MAAM,EACjE,CAMAW,qBDtWOf,ECuWe2D,GAAG,QAAQzR,MAAO0R,IAChC,IAAK,MAAMrB,KAAQqB,EAEXzR,KAAKsP,gBAAgB,CAAEvB,GAAIqC,EAAKF,KAAM9B,KAAMgC,EAAKhC,OACjDpO,KAAKgQ,WAAW,CAAEjC,GAAIqC,EAAKF,KAAM9B,KAAMgC,EAAKhC,OAIhDpO,KAAK8P,cE8QN,KF9QiC4B,gBAAgBtB,GACpD,GAER,E,iBGtXQ,IAAIuB,YACJ,IAAIC,Y,kBF8DT,IAAI,EAAO,CAAC,EA4dZ,MAAM,EAAU,IAAI,EAsDpB,SAASC,IAEZ,EAAKC,2BAA2BC,UAAY,gBAG5C,EAAKC,2BAA2BD,UAAY,gBAG5C,EAAKE,2BAA2BF,UAAY,gBAC5C,EAAKG,yBAAyBH,UAAY,iBAI1C,EAAKI,4BAA4BJ,UAAY,gBAC7C,EAAKK,0BAA0BL,UAAY,iBAG3C,EAAKM,8BAA8BN,UAAY,gBAC/C,EAAKO,4BAA4BP,UAAY,gBACjD,CAsCOhS,eAAewS,EAAmBC,EAAUC,GAAQ,GAEvD,MAAMC,QAAe,WAAiB,GAEtC,GAAIA,EAAQ,CAER,MAAMC,GACAF,EAAQ,IAAsB,KAAgB,EAAQC,GAEtD,OAAEE,EAAM,QAAEC,GAzCjB,SAAgCC,GAEnC,IAAIF,EAASE,EAGb,MAAMD,EAAUE,KAAKC,kBAAkB,YAAYvF,SAC/C,iBAEE,CACIZ,MAAO,WACPoG,SAAU,EACVC,gBAAiB,gBAErB,CAAEC,sBAAuB,EAAGC,sBAAuB,GAWzD,MAAO,CAAER,SAAQC,UACrB,CAgBoCQ,CAAuBV,GAGnDH,EAAST,UAAYa,EAAOU,eAAe,QAAST,EACxD,CACJ,CAEO,SAAS,EAAWU,GAAY,GACnC,MAAMC,EAAW,EAAQzC,aAIzB,GAAIwC,EAAW,CAEX,MAAME,GALKD,EAAW,GAKAE,QAAQxS,GACxByS,EAAOF,EAAOtT,OACpB,EAAKyT,cAAc5G,UAAYM,EAC3BmG,EACAE,GAAQ,GAAK,OAAS,QAE1B,EAAKE,mBAAmB7G,UACpBM,EAAemG,GAAU,IAAM,iBAGnC5B,IAGAU,EAAmB,EAAKuB,mBAC5B,CAEA,OAAON,CACX,CAEO,SAAS,EAAkBD,GAAY,GAC1C,MAAMC,EAAW,EAAQjC,sBAGzB,GAAIgC,EAAW,CAEX,MAAME,GAJKD,EAAW,GAIAE,QAAQxS,GACxByS,EAAOF,EAAOtT,OACpB,EAAK4T,qBAAqB/G,UAAYM,EAClCmG,EACAE,GAAQ,GAAK,OAAS,QAE1B,EAAKK,qBAAqBhH,UACtBM,EAAemG,GAAU,IAAM,iBAGnC5B,IAGAU,EAAmB,EAAK0B,oBAAoB,EAChD,CAEA,OAAOT,CACX,CAgpEA,SAASU,EAAa5T,GAClB,MAAM8L,EAAU,GAAG,6BNx+EhB,SAAsB+H,GACzB,MAAMC,EAAU7H,SAASC,cAAc,OAEvC,OADA4H,EAAQrC,UAAYoC,EACbC,EAAQpH,SACnB,CMo+E8D,CACtD1M,EAAE8L,SAAW9L,EAAE+T,UAEnB,IACI,EAAY,UAAWjI,EAK3B,CAJE,MAAOgD,GAGLpE,MAAMoB,EACV,CACJ,CAz0EyB,oBA+0EzB,IACInB,OAAOoC,iBAAiB,QAAS6G,GACjCjJ,OAAOoC,iBAAiB,qBAAsB6G,EACrC,CAAX,MAAO9E,GAAI,CGz1EN,SAAS,GAAc,QAAEkF,EAAO,UAAE9L,EAAS,OAAE+L,EAAS,YACzD,IAAKD,IAAY9L,EAAW,OAAO,KACnC,MAAMgM,EAAsB,qBAAXD,EAEjB,IAAIE,EAAcjM,Gb5hBKkM,Ea6hBNlM,Eb5hBV,EAAAxK,OAAA,KAAY0W,EAAK,Qa6hBlB,KAA4BJ,EAASE,Gb9hBxC,IAAoBE,EagiBvB,GAAe,qBAAXH,EAA+B,CAC/B,GAA2B,KAAvBE,EAAYtU,OAEZ,MAAM,IAAI8L,MAAM,8CAEpB,OAAO,EAAWwI,EACtB,CAMA,GAJ2B,KAAvBA,EAAYtU,SACZsU,EAnCR,SAA2BA,GACvB,GAA0B,IAAtBA,EAAYtU,OACZ,MAAM,IAAI8L,MAAM,sDACpB,MAAM0I,EAAIF,EAAYG,MAAM,EAAG,IAI/B,MAAO,CAHGH,EAAYG,MAAM,IAGlB,IAAM,GAAM,EAAI,EAAI,KAAMD,EACxC,CA2BsBE,CAAkBJ,IAGV,IAAtBA,EAAYtU,OACZ,MAAM,IAAI8L,MAAM,sBAGpB,GAAe,mBAAXsI,EACA,OAAO,EAAWE,GAItB,MAAMK,GAAgB,OAAO,IAAIlJ,WAAW6I,IAGtCM,GAAsB,EAAAC,EAAA,GAAUF,GAGhCG,EAAoB,IAAIrJ,WTrjBE,IJO7B,IAAiBsJ,Ea+iBpBD,EAAkB,GAAK,yBACvB,EAAaA,EAAmBF,EAAqB,GAMrD,MAAMI,GbtjBcD,EamjBYD,GbljBzB,QAAO,OAAO,IAAIrJ,WAAWsJ,MaqjBGN,MAAM,EAAG,GAG1CQ,EAAgB,IAAIxJ,WT9jBDyJ,ISmkBzB,OAJA,EAAaD,EAAeH,EAAmB,GAC/C,EAAaG,EAAeD,ETlkBI,ISqkBzB,WAAYC,EACvB,C,qDA5N2B,IAAIhK,IAAI,CAE/B,CAAC,MAAO,oCACR,CAAC,MAAO,oCACR,CAAC,MAAO,2CACR,CAAC,MAAO,+CACR,CAAC,MAAO,+CACR,CAAC,MAAO,+CACR,CAAC,MAAO,uCACR,CAAC,MAAO,yCCzXZkK,UAAY,SAAUC,GAClB,OAAa,CACT,MAAMC,EAAW,CAAC,EAClBA,EAASC,KAAO,IAEhBD,EAASE,IAAM,EAAc,CAAEpB,QAASkB,EAASC,OACjDE,YAAYH,EAChB,CACJ,C,iFCVII,EAA2B,CAAC,EAGhC,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,QAAqBzW,IAAjB0W,EACH,OAAOA,EAAaC,QAGrB,IAAIC,EAASL,EAAyBE,GAAY,CACjD/H,GAAI+H,EACJI,QAAQ,EACRF,QAAS,CAAC,GAUX,OANAG,EAAoBL,GAAUM,KAAKH,EAAOD,QAASC,EAAQA,EAAOD,QAASH,GAG3EI,EAAOC,QAAS,EAGTD,EAAOD,OACf,CAGAH,EAAoBQ,EAAIF,EAGxBN,EAAoBlB,EAAI,KAGvB,IAAI2B,EAAsBT,EAAoBU,OAAElX,EAAW,CAAC,IAAI,MAAM,IAAOwW,EAAoB,SAEjG,OADsBA,EAAoBU,EAAED,EAClB,ElBpCvB3Y,EAAW,GACfkY,EAAoBU,EAAI,CAACC,EAAQC,EAAUC,EAAIC,KAC9C,IAAGF,EAAH,CAMA,IAAIG,EAAeC,IACnB,IAAS3K,EAAI,EAAGA,EAAIvO,EAASwC,OAAQ+L,IAAK,CAGzC,IAFA,IAAKuK,EAAUC,EAAIC,GAAYhZ,EAASuO,GACpC4K,GAAY,EACPC,EAAI,EAAGA,EAAIN,EAAStW,OAAQ4W,MACpB,EAAXJ,GAAsBC,GAAgBD,IAAa1W,OAAOC,KAAK2V,EAAoBU,GAAGS,OAAOC,GAASpB,EAAoBU,EAAEU,GAAKR,EAASM,MAC9IN,EAASS,OAAOH,IAAK,IAErBD,GAAY,EACTH,EAAWC,IAAcA,EAAeD,IAG7C,GAAGG,EAAW,CACbnZ,EAASuZ,OAAOhL,IAAK,GACrB,IAAIiL,EAAIT,SACErX,IAAN8X,IAAiBX,EAASW,EAC/B,CACD,CACA,OAAOX,CAnBP,CAJCG,EAAWA,GAAY,EACvB,IAAI,IAAIzK,EAAIvO,EAASwC,OAAQ+L,EAAI,GAAKvO,EAASuO,EAAI,GAAG,GAAKyK,EAAUzK,IAAKvO,EAASuO,GAAKvO,EAASuO,EAAI,GACrGvO,EAASuO,GAAK,CAACuK,EAAUC,EAAIC,EAqBjB,EmBzBdd,EAAoBuB,EAAKnB,IACxB,IAAIoB,EAASpB,GAAUA,EAAOqB,WAC7B,IAAOrB,EAAiB,QACxB,IAAM,EAEP,OADAJ,EAAoB0B,EAAEF,EAAQ,CAAEjG,EAAGiG,IAC5BA,CAAM,ElBNVxZ,EAAWoC,OAAOuX,eAAkBC,GAASxX,OAAOuX,eAAeC,GAASA,GAASA,EAAa,UAQtG5B,EAAoB6B,EAAI,SAASC,EAAOC,GAEvC,GADU,EAAPA,IAAUD,EAAQ3X,KAAK2X,IAChB,EAAPC,EAAU,OAAOD,EACpB,GAAoB,iBAAVA,GAAsBA,EAAO,CACtC,GAAW,EAAPC,GAAaD,EAAML,WAAY,OAAOK,EAC1C,GAAW,GAAPC,GAAoC,mBAAfD,EAAME,KAAqB,OAAOF,CAC5D,CACA,IAAIG,EAAK7X,OAAOuL,OAAO,MACvBqK,EAAoBsB,EAAEW,GACtB,IAAIC,EAAM,CAAC,EACXna,EAAiBA,GAAkB,CAAC,KAAMC,EAAS,CAAC,GAAIA,EAAS,IAAKA,EAASA,IAC/E,IAAI,IAAIK,EAAiB,EAAP0Z,GAAYD,EAAyB,iBAAXzZ,KAAyBN,EAAeoa,QAAQ9Z,GAAUA,EAAUL,EAASK,GACxH+B,OAAOgY,oBAAoB/Z,GAASga,SAASjB,GAASc,EAAId,GAAO,IAAOU,EAAMV,KAI/E,OAFAc,EAAa,QAAI,IAAM,EACvBlC,EAAoB0B,EAAEO,EAAIC,GACnBD,CACR,EmBxBAjC,EAAoB0B,EAAI,CAACvB,EAASmC,KACjC,IAAI,IAAIlB,KAAOkB,EACXtC,EAAoBuC,EAAED,EAAYlB,KAASpB,EAAoBuC,EAAEpC,EAASiB,IAC5EhX,OAAOoY,eAAerC,EAASiB,EAAK,CAAEqB,YAAY,EAAMlQ,IAAK+P,EAAWlB,IAE1E,ECNDpB,EAAoB0C,EAAI,CAAC,EAGzB1C,EAAoBvV,EAAKkY,GACjBtJ,QAAQuJ,IAAIxY,OAAOC,KAAK2V,EAAoB0C,GAAGpH,QAAO,CAACuH,EAAUzB,KACvEpB,EAAoB0C,EAAEtB,GAAKuB,EAASE,GAC7BA,IACL,KCNJ7C,EAAoB8C,EAAKH,GAEjB,KAAOA,EAAU,UCFzB3C,EAAoB+C,SAAYJ,IAEf,ECHjB3C,EAAoBgD,EAAI,WACvB,GAA0B,iBAAfC,WAAyB,OAAOA,WAC3C,IACC,OAAO9Y,MAAQ,IAAI+Y,SAAS,cAAb,EAGhB,CAFE,MAAOzY,GACR,GAAsB,iBAAX2K,OAAqB,OAAOA,MACxC,CACA,CAPuB,GCAxB4K,EAAoBuC,EAAI,CAACX,EAAKuB,IAAU/Y,OAAOgZ,UAAUC,eAAe9C,KAAKqB,EAAKuB,GCClFnD,EAAoBsB,EAAKnB,IACH,oBAAXmD,QAA0BA,OAAOC,aAC1CnZ,OAAOoY,eAAerC,EAASmD,OAAOC,YAAa,CAAEzB,MAAO,WAE7D1X,OAAOoY,eAAerC,EAAS,aAAc,CAAE2B,OAAO,GAAO,ECL9D9B,EAAoBwD,IAAOpD,IAC1BA,EAAOqD,MAAQ,GACVrD,EAAOsD,WAAUtD,EAAOsD,SAAW,IACjCtD,G,MCHR,IAAIuD,EACA3D,EAAoBgD,EAAEY,gBAAeD,EAAY3D,EAAoBgD,EAAE3N,SAAW,IACtF,IAAIqB,EAAWsJ,EAAoBgD,EAAEtM,SACrC,IAAKiN,GAAajN,IACbA,EAASmN,gBACZF,EAAYjN,EAASmN,cAAcC,MAC/BH,GAAW,CACf,IAAII,EAAUrN,EAASsN,qBAAqB,UACzCD,EAAQzZ,SAAQqZ,EAAYI,EAAQA,EAAQzZ,OAAS,GAAGwZ,IAC5D,CAID,IAAKH,EAAW,MAAM,IAAIvN,MAAM,yDAChCuN,EAAYA,EAAUM,QAAQ,OAAQ,IAAIA,QAAQ,QAAS,IAAIA,QAAQ,YAAa,KACpFjE,EAAoBkE,EAAIP,C,WCfxB3D,EAAoBxE,EAAI2I,KAAK9O,SAAW,GAIxC,IAAI+O,EAAkB,CACrB,GAAI,GAgBLpE,EAAoB0C,EAAErM,EAAI,CAACsM,EAASE,KAE/BuB,EAAgBzB,IAElBiB,cAAc5D,EAAoBkE,EAAIlE,EAAoB8C,EAAEH,GAE9D,EAGD,IAAI0B,EAAqBF,KAAsB,gBAAIA,KAAsB,iBAAK,GAC1EG,EAA6BD,EAAmB/J,KAAKiK,KAAKF,GAC9DA,EAAmB/J,KAvBCkK,IACnB,IAAK5D,EAAU6D,EAAaC,GAAWF,EACvC,IAAI,IAAIvE,KAAYwE,EAChBzE,EAAoBuC,EAAEkC,EAAaxE,KACrCD,EAAoBQ,EAAEP,GAAYwE,EAAYxE,IAIhD,IADGyE,GAASA,EAAQ1E,GACdY,EAAStW,QACd8Z,EAAgBxD,EAAS+D,OAAS,EACnCL,EAA2BE,EAAK,C,K3BnB7Bvc,EAAO+X,EAAoBlB,EAC/BkB,EAAoBlB,EAAI,IAChBzF,QAAQuJ,IAAI,CAClB5C,EAAoBvV,EAAE,KACtBuV,EAAoBvV,EAAE,OACpBuX,KAAK/Z,G4BJT,IAAIwY,EAAsBT,EAAoBlB,I","sources":["webpack://MPW/webpack/runtime/chunk loaded","webpack://MPW/webpack/runtime/create fake namespace object","webpack://MPW/webpack/runtime/startup chunk dependencies","webpack://MPW/./scripts/utils.js","webpack://MPW/./scripts/chain_params.js","webpack://MPW/./scripts/prices.js","webpack://MPW/./scripts/settings.js","webpack://MPW/./scripts/misc.js","webpack://MPW/./scripts/script.js","webpack://MPW/./scripts/database.js","webpack://MPW/./scripts/i18n.js","webpack://MPW/./scripts/event_bus.js","webpack://MPW/./scripts/mempool.js","webpack://MPW/./scripts/global.js","webpack://MPW/./scripts/network.js","webpack://MPW/./scripts/aes-gcm.js","webpack://MPW/./scripts/wallet.js","webpack://MPW/./scripts/vanitygen_worker.js","webpack://MPW/webpack/bootstrap","webpack://MPW/webpack/runtime/compat get default export","webpack://MPW/webpack/runtime/define property getters","webpack://MPW/webpack/runtime/ensure chunk","webpack://MPW/webpack/runtime/get javascript chunk filename","webpack://MPW/webpack/runtime/get mini-css chunk filename","webpack://MPW/webpack/runtime/global","webpack://MPW/webpack/runtime/hasOwnProperty shorthand","webpack://MPW/webpack/runtime/make namespace object","webpack://MPW/webpack/runtime/node module decorator","webpack://MPW/webpack/runtime/publicPath","webpack://MPW/webpack/runtime/importScripts chunk loading","webpack://MPW/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var next = __webpack_require__.x;\n__webpack_require__.x = () => {\n\treturn Promise.all([\n\t\t__webpack_require__.e(621),\n\t\t__webpack_require__.e(369)\n\t]).then(next);\n};","import { Buffer } from 'buffer';\nimport { sha256 } from '@noble/hashes/sha256';\n\nexport function hexToBytes(str) {\n return Buffer.from(str, 'hex');\n}\n\nexport function bytesToHex(bytes) {\n return Buffer.from(bytes).toString('hex');\n}\n\n/**\n * Double SHA256 hash a byte array\n * @param {Array} buff - Bytes to hash\n * @returns {Uint8Array} Hash buffer\n */\nexport function dSHA256(buff) {\n return sha256(sha256(new Uint8Array(buff)));\n}\n","// In most BTC-derived coins, the below parameters can be found in the 'src/chainparams.cpp' Mainnet configuration.\n// These below params share the same names as the CPP params, so finding and editing these is easy-peasy!\n// <[network_byte] [32_byte_payload] [0x01] [4_byte_checksum]>\nexport const PRIVKEY_BYTE_LENGTH = 38;\n\nexport const COIN_DECIMALS = 8;\nexport const COIN = 10 ** 8;\n\n/** The maximum gap (absence of transactions within a range of derived addresses) before an account search ends */\nexport const MAX_ACCOUNT_GAP = 20;\n\n/* Internal tweaking parameters */\n// A new encryption password must be 'at least' this long.\nexport const MIN_PASS_LENGTH = 6;\n\n/** BIP21 coin prefix */\nexport const BIP21_PREFIX = 'pivx';\n\n/* chainparams */\nexport const cChainParams = {\n current: null,\n main: {\n name: 'mainnet',\n collateralInSats: 10000 * COIN,\n isTestnet: false,\n TICKER: 'PIV',\n PUBKEY_PREFIX: ['D'],\n STAKING_PREFIX: 'S',\n PUBKEY_ADDRESS: 30,\n SECRET_KEY: 212,\n BIP44_TYPE: 119,\n BIP44_TYPE_LEDGER: 77,\n PROTOCOL_VERSION: 70926,\n MASTERNODE_PORT: 51472,\n // A list of Labs-trusted explorers\n Explorers: [\n // Display name Blockbook-compatible API base\n { name: 'rockdev', url: 'https://explorer.rockdev.org' },\n { name: 'zkBitcoin', url: 'https://zkbitcoin.com' },\n { name: 'Duddino', url: 'https://explorer.duddino.com' },\n ],\n Nodes: [{ name: 'Duddino', url: 'https://rpc.duddino.com/mainnet' }],\n Consensus: {\n // Network upgrades\n UPGRADE_V6_0: undefined,\n },\n budgetCycleBlocks: 43200,\n proposalFee: 50 * COIN,\n maxPaymentCycles: 6,\n maxPayment: 10 * 43200 * COIN, // 43200 blocks of 10 PIV\n },\n testnet: {\n name: 'testnet',\n collateralInSats: 10000 * COIN,\n isTestnet: true,\n TICKER: 'tPIV',\n PUBKEY_PREFIX: ['x', 'y'],\n STAKING_PREFIX: 'W',\n PUBKEY_ADDRESS: 139,\n SECRET_KEY: 239,\n BIP44_TYPE: 1,\n BIP44_TYPE_LEDGER: 1,\n PROTOCOL_VERSION: 70926,\n MASTERNODE_PORT: 51474,\n // A list of Labs-trusted explorers\n Explorers: [\n // Display name Blockbook-compatible API base\n { name: 'rockdev', url: 'https://testnet.rockdev.org' },\n ],\n Nodes: [{ name: 'Duddino', url: 'https://rpc.duddino.com/testnet' }],\n Consensus: {\n // Network upgrades\n UPGRADE_V6_0: undefined,\n },\n budgetCycleBlocks: 144,\n proposalFee: 50 * COIN,\n maxPaymentCycles: 20,\n maxPayment: 10 * 144 * COIN, // 144 blocks of 10 tPIV\n },\n};\n// Set default chain\ncChainParams.current = cChainParams.main;\n","import { getBalance } from './global';\nimport { isEmpty } from './misc';\nimport { cMarket, fillCurrencySelect } from './settings';\n\n/**\n * CoinGecko's endpoint for PIVX data, optimised for least bandwidth\n * - No localisation, tickers, community data, developer data or sparklines\n */\nexport const COINGECKO_ENDPOINT =\n 'https://api.coingecko.com/api/v3/coins/pivx?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false&sparkline=false';\n\n/**\n * The generic market data source template, used to build site-specific classes\n */\nexport class MarketSource {\n /** The storage object for raw market data */\n cData = {};\n\n /** The name of the market source */\n strName = '';\n\n /** The customised API endpoint of the market source */\n strEndpoint = '';\n\n /**\n * Ensure a market data cache exists, if not, fetch it and resume\n */\n async ensureCacheExists() {\n if (!this.cData || !Object.keys(this.cData).length) await this.fetch();\n }\n\n /**\n * Fetches the raw market source data\n * @returns {Promise}\n */\n async fetch() {\n try {\n return (this.cData = await (await fetch(this.strEndpoint)).json());\n } catch (e) {\n console.warn('CoinGecko: Failed to fetch prices!');\n console.warn(e);\n return null;\n }\n }\n}\n\n/**\n * The CoinGecko market data source\n */\nexport class CoinGecko extends MarketSource {\n constructor() {\n super();\n this.strName = 'CoinGecko';\n this.strEndpoint = COINGECKO_ENDPOINT;\n }\n\n /**\n * Get the price in a specific display currency\n * @param {string} strCurrency - The CoinGecko-supported display currency\n * @return {Promise}\n */\n async getPrice(strCurrency) {\n await this.ensureCacheExists();\n return this.cData?.market_data?.current_price[strCurrency] || 0;\n }\n\n /**\n * Get a list of the supported display currencies\n * @returns {Promise>} - A list of CoinGecko-supported display currencies\n */\n async getCurrencies() {\n await this.ensureCacheExists();\n return !isEmpty(this.cData)\n ? Object.keys(this.cData.market_data.current_price)\n : [];\n }\n}\n\n/**\n * Refreshes market data from the user's data source, then re-renders currency options and price displays\n */\nexport async function refreshPriceDisplay() {\n // Refresh our price data, and if successful, update the UI\n if (!isEmpty(await cMarket.fetch())) {\n // Update the currency customisation menu from the selected data source\n await fillCurrencySelect();\n\n // Update price values\n getBalance(true);\n }\n}\n","import {\n doms,\n getBalance,\n getStakingBalance,\n mempool,\n refreshChainData,\n renderActivityGUI,\n setDisplayForAllWalletOptions,\n updateActivityGUI,\n updateEncryptionGUI,\n updateGovernanceTab,\n} from './global.js';\nimport {\n hasEncryptedWallet,\n importWallet,\n masterKey,\n setMasterKey,\n} from './wallet.js';\nimport { cChainParams } from './chain_params.js';\nimport { setNetwork, ExplorerNetwork, getNetwork } from './network.js';\nimport { confirmPopup, createAlert, isEmpty } from './misc.js';\nimport {\n switchTranslation,\n ALERTS,\n translation,\n arrActiveLangs,\n tr,\n} from './i18n.js';\nimport { CoinGecko, refreshPriceDisplay } from './prices.js';\nimport { Database } from './database.js';\n\n// --- Default Settings\n/** A mode that emits verbose console info for internal MPW operations */\nexport let debug = false;\n/**\n * The user-selected display currency from market-aggregator sites\n * @type {string}\n */\nexport let strCurrency = 'usd';\n/**\n * The global market data source\n * @type {CoinGecko}\n */\nexport let cMarket = new CoinGecko();\n/** The user-selected explorer, used for most of MPW's data synchronisation */\nexport let cExplorer = cChainParams.current.Explorers[0];\n/** The user-selected MPW node, used for alternative blockchain data */\nexport let cNode = cChainParams.current.Nodes[0];\n/** A mode which allows MPW to automatically select it's data sources */\nexport let fAutoSwitch = true;\n/** The active Cold Staking address: default is the PIVX Labs address */\nexport let strColdStakingAddress = 'SdgQDpS8jDRJDX8yK8m9KnTMarsE84zdsy';\n/** The decimals to display for the wallet balance */\nexport let nDisplayDecimals = 2;\n\nlet transparencyReport;\n\nexport class Settings {\n /**\n * @type {String} analytics level\n */\n analytics;\n /**\n * @type {String} Explorer url to use\n */\n explorer;\n /**\n * @type {String} Node url to use\n */\n node;\n /**\n * @type {Boolean} The Auto-Switch mode state\n */\n autoswitch;\n /**\n * @type {String} The user's active Cold Staking address\n */\n coldAddress;\n /**\n * @type {String} translation to use\n */\n translation;\n /**\n * @type {String} Currency to display\n */\n displayCurrency;\n /**\n * @type {number} The decimals to display for the wallet balance\n */\n displayDecimals;\n constructor({\n analytics,\n explorer,\n node,\n autoswitch = true,\n coldAddress = strColdStakingAddress,\n translation = '',\n displayCurrency = 'usd',\n displayDecimals = nDisplayDecimals,\n } = {}) {\n this.analytics = analytics;\n this.explorer = explorer;\n this.node = node;\n this.autoswitch = autoswitch;\n this.coldAddress = coldAddress;\n this.translation = translation;\n this.displayCurrency = displayCurrency;\n this.displayDecimals = displayDecimals;\n }\n}\n\n// A list of statistic keys and their descriptions\nexport let STATS = {\n // Stat key // Description of the stat, it's data, and it's purpose\n hit: 'A ping indicating an app load, no unique data is sent.',\n time_to_sync: 'The time in seconds it took for MPW to last synchronise.',\n transaction:\n 'A ping indicating a Tx, no unique data is sent, but may be inferred from on-chain time.',\n};\n\nexport const cStatKeys = Object.keys(STATS);\n\n// A list of Analytics 'levels' at which the user may set depending on their privacy preferences\n// NOTE: When changing Level Names, ensure the i18n system is updated to support them too\nlet arrAnalytics = [\n // Statistic level // Allowed statistics\n { name: 'Disabled', stats: [] },\n { name: 'Minimal', stats: [STATS.hit, STATS.time_to_sync] },\n {\n name: 'Balanced',\n stats: [STATS.hit, STATS.time_to_sync, STATS.transaction],\n },\n];\n\nexport let cAnalyticsLevel = arrAnalytics[2];\n\n// Users need not look below here.\n// ------------------------------\n// Global Keystore / Wallet Information\n\n// --- DOM Cache\nexport async function start() {\n //TRANSLATIONS\n //to make translations work we need to change it so that we just enable or disable the visibility of the text\n doms.domTestnet.style.display = cChainParams.current.isTestnet\n ? ''\n : 'none';\n doms.domDebug.style.display = debug ? '' : 'none';\n\n // Hook up the 'currency' select UI\n document.getElementById('currency').onchange = function (evt) {\n setCurrency(evt.target.value);\n };\n\n // Hook up the 'display decimals' slider UI\n doms.domDisplayDecimalsSlider.onchange = function (evt) {\n setDecimals(Number(evt.target.value));\n };\n\n // Hook up the 'explorer' select UI\n document.getElementById('explorer').onchange = function (evt) {\n setExplorer(\n cChainParams.current.Explorers.find(\n (a) => a.url === evt.target.value\n )\n );\n };\n\n // Hook up the 'translation' select UI\n document.getElementById('translation').onchange = function (evt) {\n setTranslation(evt.target.value);\n };\n\n // Hook up the 'analytics' select UI\n document.getElementById('analytics').onchange = function (evt) {\n setAnalytics(arrAnalytics.find((a) => a.name === evt.target.value));\n };\n\n await Promise.all([\n fillExplorerSelect(),\n fillNodeSelect(),\n fillTranslationSelect(),\n ]);\n\n // Fetch price data, then fetch chain data\n if (getNetwork().enabled) {\n refreshPriceDisplay().finally(refreshChainData);\n }\n\n const database = await Database.getInstance();\n\n // Fetch settings from Database\n const {\n analytics: strSettingAnalytics,\n autoswitch,\n coldAddress,\n displayCurrency,\n displayDecimals,\n } = await database.getSettings();\n\n // Set the Cold Staking address\n strColdStakingAddress = coldAddress;\n\n // Set any Toggles to their default or DB state\n fAutoSwitch = autoswitch;\n doms.domAutoSwitchToggle.checked = fAutoSwitch;\n\n // Set the display currency\n strCurrency = doms.domCurrencySelect.value = displayCurrency;\n\n // Set the display decimals\n nDisplayDecimals = displayDecimals;\n doms.domDisplayDecimalsSlider.value = nDisplayDecimals;\n\n // Apply translations to the transparency report\n STATS = {\n // Stat key // Description of the stat, it's data, and it's purpose\n hit: translation.hit,\n time_to_sync: translation.time_to_sync,\n transaction: translation.transaction,\n };\n transparencyReport = translation.transparencyReport;\n arrAnalytics = [\n // Statistic level // Allowed statistics\n { name: 'Disabled', stats: [] },\n { name: 'Minimal', stats: [STATS.hit, STATS.time_to_sync] },\n {\n name: 'Balanced',\n stats: [STATS.hit, STATS.time_to_sync, STATS.transaction],\n },\n ];\n\n // Initialise status icons as their default variables\n doms.domNetwork.innerHTML =\n '';\n\n // Honour the \"Do Not Track\" header by default\n if (!strSettingAnalytics && navigator.doNotTrack === '1') {\n // Disabled\n setAnalytics(arrAnalytics[0], true);\n doms.domAnalyticsDescriptor.innerHTML =\n '
Analytics disabled to honour \"Do Not Track\" browser setting, you may manually enable if desired, though!
';\n } else {\n // Load from storage, or use defaults\n setAnalytics(\n (cAnalyticsLevel =\n arrAnalytics.find((a) => a.name === strSettingAnalytics) ||\n cAnalyticsLevel),\n true\n );\n }\n\n // Add each analytics level into the UI selector\n fillAnalyticSelect();\n}\n// --- Settings Functions\nexport async function setExplorer(explorer, fSilent = false) {\n const database = await Database.getInstance();\n database.setSettings({ explorer: explorer.url });\n cExplorer = explorer;\n\n // Enable networking + notify if allowed\n const network = new ExplorerNetwork(cExplorer.url, masterKey);\n setNetwork(network);\n\n // Update the selector UI\n doms.domExplorerSelect.value = cExplorer.url;\n\n if (!fSilent)\n createAlert(\n 'success',\n tr(ALERTS.SWITCHED_EXPLORERS, [{ explorerName: cExplorer.name }]),\n 2250\n );\n}\n\nasync function setNode(node, fSilent = false) {\n cNode = node;\n const database = await Database.getInstance();\n database.setSettings({ node: node.url });\n\n // Enable networking + notify if allowed\n getNetwork().enable();\n if (!fSilent)\n createAlert(\n 'success',\n tr(ALERTS.SWITCHED_NODE, [{ node: cNode.name }]),\n 2250\n );\n}\n\n//TRANSLATION\n/**\n * Switches the translation and sets the translation preference to database\n * @param {string} strLang\n */\nexport async function setTranslation(strLang) {\n switchTranslation(strLang);\n const database = await Database.getInstance();\n database.setSettings({ translation: strLang });\n doms.domTranslationSelect.value = strLang;\n}\n\n/**\n * Sets and saves the display currency setting in runtime and database\n * @param {string} currency - The currency string name\n */\nasync function setCurrency(currency) {\n strCurrency = currency;\n const database = await Database.getInstance();\n database.setSettings({ displayCurrency: strCurrency });\n // Update the UI to reflect the new currency\n getBalance(true);\n getStakingBalance(true);\n}\n\n/**\n * Sets and saves the display decimals setting in runtime and database\n * @param {number} decimals - The decimals to set for the display\n */\nasync function setDecimals(decimals) {\n nDisplayDecimals = decimals;\n const database = await Database.getInstance();\n database.setSettings({ displayDecimals: nDisplayDecimals });\n // Update the UI to reflect the new decimals\n getBalance(true);\n getStakingBalance(true);\n}\n\n/**\n * Sets and saves the active Cold Staking address\n * @param {string} strColdAddress - The Cold Staking address\n */\nexport async function setColdStakingAddress(strColdAddress) {\n strColdStakingAddress = strColdAddress;\n const database = await Database.getInstance();\n database.setSettings({ coldAddress: strColdAddress });\n}\n\n/**\n * Fills the translation dropbox on the settings page\n */\nasync function fillTranslationSelect() {\n while (doms.domTranslationSelect.options.length > 0) {\n doms.domTranslationSelect.remove(0);\n }\n\n // Add each language into the UI selector\n for (const cLang of arrActiveLangs) {\n const opt = document.createElement('option');\n opt.innerHTML = `${cLang.emoji} ${cLang.code.toUpperCase()}`;\n opt.value = cLang.code;\n doms.domTranslationSelect.appendChild(opt);\n }\n\n const database = await Database.getInstance();\n const { translation: strLang } = await database.getSettings();\n // And update the UI to reflect them (default to English if none)\n doms.domTranslationSelect.value = strLang;\n}\n\n/**\n * Fills the display currency dropbox on the settings page\n */\nexport async function fillCurrencySelect() {\n const arrCurrencies = await cMarket.getCurrencies();\n\n // Only update if we have a currency list\n if (!isEmpty(arrCurrencies)) {\n while (doms.domCurrencySelect.options.length > 0) {\n doms.domCurrencySelect.remove(0);\n }\n\n // Add each data source currency into the UI selector\n for (const currency of arrCurrencies) {\n const opt = document.createElement('option');\n opt.innerHTML = currency.toUpperCase();\n opt.value = currency;\n doms.domCurrencySelect.appendChild(opt);\n }\n }\n\n const database = await Database.getInstance();\n const { displayCurrency } = await database.getSettings();\n\n // And update the UI to reflect them\n strCurrency = doms.domCurrencySelect.value = displayCurrency;\n}\n\n/**\n * Fills the Analytics Settings UI\n */\nexport function fillAnalyticSelect() {\n const domAnalyticsSelect = document.getElementById('analytics');\n domAnalyticsSelect.innerHTML = '';\n for (const analLevel of arrAnalytics) {\n const opt = document.createElement('option');\n // Apply translation to the display HTML\n opt.value = analLevel.name;\n opt.innerHTML = translation['analytic' + analLevel.name];\n domAnalyticsSelect.appendChild(opt);\n }\n}\n\nasync function setAnalytics(level, fSilent = false) {\n cAnalyticsLevel = level;\n const database = await Database.getInstance();\n await database.setSettings({ analytics: level.name });\n\n // For total transparency, we'll 'describe' the various analytic keys of this chosen level\n let strDesc = '
--- ' + transparencyReport + ' ---

',\n i = 0;\n const nLongestKeyLen = cStatKeys.reduce((prev, e) =>\n prev.length >= e.length ? prev : e\n ).length;\n for (i; i < cAnalyticsLevel.stats.length; i++) {\n const cStat = cAnalyticsLevel.stats[i];\n // This formats Stat keys into { $key $(padding) $description }\n strDesc +=\n cStatKeys\n .find((a) => STATS[a] === cStat)\n .padEnd(nLongestKeyLen, ' ') +\n ': ' +\n cStat +\n '
';\n }\n\n // Set display + notify if allowed\n doms.domAnalyticsDescriptor.innerHTML =\n cAnalyticsLevel.name === arrAnalytics[0].name\n ? ''\n : '
' +\n              strDesc +\n              '
';\n if (!fSilent)\n createAlert(\n 'success',\n tr(ALERTS.SWITCHED_ANALYTICS, [\n { level: translation['analytic' + cAnalyticsLevel.name] },\n ]),\n 2250\n );\n}\n\n/**\n * Toggle between Mainnet and Testnet\n */\nexport async function toggleTestnet() {\n const cNextNetwork = cChainParams.current.isTestnet\n ? cChainParams.main\n : cChainParams.testnet;\n\n // If the current wallet is not saved, we'll ask the user for confirmation, since they'll lose their wallet if they switch with an unsaved wallet!\n if (masterKey && !(await hasEncryptedWallet())) {\n const fContinue = await confirmPopup({\n title: tr(translation.netSwitchUnsavedWarningTitle, [\n { network: cChainParams.current.name },\n ]),\n html: `\n ${tr(translation.netSwitchUnsavedWarningSubtitle, [\n { network: cChainParams.current.name },\n ])}\n
\n ${tr(translation.netSwitchUnsavedWarningSubtext, [\n { network: cNextNetwork.name },\n ])}\n
\n
\n ${\n translation.netSwitchUnsavedWarningConfirmation\n }\n `,\n });\n\n if (!fContinue) {\n // Kick back the \"toggle\" switch\n doms.domTestnetToggler.checked = cChainParams.current.isTestnet;\n return;\n }\n }\n\n // Update current chain config\n cChainParams.current = cNextNetwork;\n\n // Update UI and static tickers\n doms.domTestnet.style.display = cChainParams.current.isTestnet\n ? ''\n : 'none';\n doms.domGuiBalanceTicker.innerText = cChainParams.current.TICKER;\n doms.domGuiBalanceStakingTicker.innerText = cChainParams.current.TICKER;\n doms.domPrefixNetwork.innerText =\n cChainParams.current.PUBKEY_PREFIX.join(' or ');\n\n // Update testnet toggle in settings\n doms.domTestnetToggler.checked = cChainParams.current.isTestnet;\n\n // Check if the new network has an Account\n const cNewDB = await Database.getInstance();\n const cNewAccount = await cNewDB.getAccount();\n if (cNewAccount?.publicKey) {\n // Import the new wallet (overwriting the existing in-memory wallet)\n await importWallet({ newWif: cNewAccount.publicKey });\n } else {\n // Nuke the Master Key\n setMasterKey(null);\n\n // Hide all Dashboard info, kick the user back to the \"Getting Started\" area\n doms.domGenKeyWarning.style.display = 'none';\n doms.domGuiWallet.style.display = 'none';\n doms.domWipeWallet.hidden = true;\n doms.domRestoreWallet.hidden = true;\n\n // Set the \"Wallet Options\" display CSS to it's Default\n setDisplayForAllWalletOptions('');\n\n // Reset the \"Vanity\" and \"Import\" flows\n doms.domPrefix.value = '';\n doms.domPrefix.style.display = 'none';\n\n // Show \"Access Wallet\" button\n doms.domImportWallet.style.display = 'none';\n doms.domPrivKey.style.opacity = '0';\n doms.domAccessWallet.style.display = '';\n doms.domAccessWalletBtn.style.display = '';\n\n // Hide \"Import Wallet\" so the user has to follow the `accessOrImportWallet()` flow\n doms.domImportWallet.style.display = 'none';\n }\n\n // Re-render the Activity UI as empty\n await renderActivityGUI([]);\n\n mempool.UTXOs = [];\n getBalance(true);\n getStakingBalance(true);\n await updateEncryptionGUI(!!masterKey);\n await fillExplorerSelect();\n await fillNodeSelect();\n await updateActivityGUI();\n await updateGovernanceTab();\n}\n\nexport function toggleDebug() {\n debug = !debug;\n doms.domDebug.style.display = debug ? '' : 'none';\n}\n\n/**\n * Toggle the Auto-Switch mode at runtime and in DB\n */\nexport async function toggleAutoSwitch() {\n fAutoSwitch = !fAutoSwitch;\n\n // Update the setting in the DB\n const database = await Database.getInstance();\n await database.setSettings({ autoswitch: fAutoSwitch });\n}\n\nasync function fillExplorerSelect() {\n cExplorer = cChainParams.current.Explorers[0];\n\n while (doms.domExplorerSelect.options.length > 0) {\n doms.domExplorerSelect.remove(0);\n }\n\n // Add each trusted explorer into the UI selector\n for (const explorer of cChainParams.current.Explorers) {\n const opt = document.createElement('option');\n opt.value = explorer.url;\n opt.innerHTML =\n explorer.name + ' (' + explorer.url.replace('https://', '') + ')';\n doms.domExplorerSelect.appendChild(opt);\n }\n\n // Fetch settings from Database\n const database = await Database.getInstance();\n const { explorer: strSettingExplorer } = await database.getSettings();\n\n // For any that exist: load them, or use the defaults\n await setExplorer(\n cChainParams.current.Explorers.find(\n (a) => a.url === strSettingExplorer\n ) || cExplorer,\n true\n );\n\n // And update the UI to reflect them\n doms.domExplorerSelect.value = cExplorer.url;\n}\n\nasync function fillNodeSelect() {\n cNode = cChainParams.current.Nodes[0];\n\n while (doms.domNodeSelect.options.length > 0) {\n doms.domNodeSelect.remove(0);\n }\n\n // Add each trusted node into the UI selector\n for (const node of cChainParams.current.Nodes) {\n const opt = document.createElement('option');\n opt.value = node.url;\n opt.innerHTML =\n node.name + ' (' + node.url.replace('https://', '') + ')';\n doms.domNodeSelect.appendChild(opt);\n }\n\n // Fetch settings from Database\n const database = await Database.getInstance();\n const { node: strSettingNode } = await database.getSettings();\n\n // For any that exist: load them, or use the defaults\n setNode(\n cChainParams.current.Nodes.find((a) => a.url === strSettingNode) ||\n cNode,\n true\n );\n\n // And update the UI to reflect them\n doms.domNodeSelect.value = cNode.url;\n}\n","import { translation } from './i18n.js';\nimport { doms } from './global.js';\nimport qrcode from 'qrcode-generator';\nimport bs58 from 'bs58';\nimport { bech32 } from 'bech32';\nimport { BIP21_PREFIX, cChainParams } from './chain_params';\nimport { dSHA256 } from './utils.js';\n\n/* MPW constants */\nexport const pubKeyHashNetworkLen = 21;\nexport const pubChksum = 4;\nexport const pubPrebaseLen = pubKeyHashNetworkLen + pubChksum;\n\n// Base58 Encoding Map\nexport const MAP_B58 =\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nexport const LEN_B58 = MAP_B58.length;\n\n/* --- UTILS --- */\n// Cryptographic Random-Gen\nexport function getSafeRand(nSize = 32) {\n return crypto.getRandomValues(new Uint8Array(nSize));\n}\n\nexport const MAP_ALPHANUMERIC =\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';\n\n/**\n * Generate a random Alpha-Numeric sequence\n * @param {number} nSize - The amount of characters to generate\n * @returns {string} - A random alphanumeric string of nSize length\n */\nexport function getAlphaNumericRand(nSize = 32) {\n let result = '';\n const randValues = getSafeRand(nSize);\n for (const byte of randValues) {\n const index = byte % MAP_ALPHANUMERIC.length;\n result += MAP_ALPHANUMERIC.charAt(index);\n }\n return result;\n}\n\n// Writes a sequence of Array-like bytes into a location within a Uint8Array\nexport function writeToUint8(arr, bytes, pos) {\n const arrLen = arr.length;\n // Sanity: ensure an overflow cannot occur, if one is detected, somewhere in MPW's state could be corrupted.\n if (arrLen - pos - bytes.length < 0) {\n const strERR =\n 'CRITICAL: Overflow detected (' +\n (arrLen - pos - bytes.length) +\n '), possible state corruption, backup and refresh advised.';\n createAlert('warning', strERR, 5000);\n throw Error(strERR);\n }\n let i = 0;\n while (pos < arrLen) arr[pos++] = bytes[i++];\n}\n\n/** Convert a 2D array into a CSV string */\nexport function arrayToCSV(data) {\n return data\n .map(\n (row) =>\n row\n .map(String) // convert every value to String\n .map((v) => v.replaceAll('\"', '\"\"')) // escape double colons\n .map((v) => `\"${v}\"`) // quote it\n .join(',') // comma-separated\n )\n .join('\\r\\n'); // rows starting on new lines\n}\n\n/** Download contents as a file */\nexport function downloadBlob(content, filename, contentType) {\n // Create a blob\n const blob = new Blob([content], { type: contentType });\n\n // Create a link to download it\n const pom = document.createElement('a');\n pom.href = URL.createObjectURL(blob);\n pom.setAttribute('download', filename);\n pom.click();\n}\n\n/**\n * Create a custom GUI Alert popup\n *\n * ### Do NOT display arbitrary / external errors:\n * - The use of `.innerHTML` allows for input styling at this cost.\n * @param {'success'|'info'|'warning'} type - The styling type of the alert\n * @param {string} message - The message to relay to the user\n * @param {number?} timeout - The time in `ms` until the alert expires (Defaults to never expiring)\n */\nexport function createAlert(type, message, timeout = 0) {\n const domAlert = document.createElement('div');\n domAlert.classList.add('notifyWrapper');\n domAlert.classList.add(type);\n setTimeout(() => {\n domAlert.style.opacity = '1';\n domAlert.style.zIndex = '999999';\n domAlert.classList.add('bounce-ani');\n domAlert.classList.add('bounce');\n }, 100);\n\n // Colors for types\n let typeIcon;\n switch (type) {\n case 'warning':\n typeIcon = 'fa-exclamation';\n break;\n case 'info':\n typeIcon = 'fa-info';\n break;\n default:\n // If no valid type is set, default to success\n type == 'success';\n typeIcon = 'fa-check';\n break;\n }\n\n // Message\n domAlert.innerHTML = `\n
\n \n
\n
\n ${message}\n
`;\n domAlert.destroy = () => {\n // Fully destroy timers + DOM elements, no memory leaks!\n clearTimeout(domAlert.timer);\n domAlert.style.opacity = '0';\n setTimeout(() => {\n domAlert.remove();\n }, 600);\n };\n // On Click: Delete alert from DOM after close animation.\n domAlert.addEventListener('click', domAlert.destroy);\n // On Timeout: Delete alert from DOM after a period of inactive time.\n if (timeout > 0) domAlert.timer = setTimeout(domAlert.destroy, timeout);\n doms.domAlertPos.appendChild(domAlert);\n}\n\n/**\n * Shows a Confirm popup with custom HTML.\n *\n * If `resolvePromise` has a value, the popup won't have\n * Confirm/Cancel buttons and will wait for the promise to resolve.\n *\n * Returns the awaited value of `resolvePromise` or `true/false` if the\n * user used a Cancel/Confirm button.\n * @param {object} options\n * @param {string?} options.title - The optional title of the popup\n * @param {string} options.html - The HTML of the popup contents\n * @param {Promise} options.resolvePromise - A promise to resolve before closing the modal\n * @param {boolean?} options.hideConfirm - Whether to hide the Confirm button or not\n * @param {boolean?} options.purpleModal - Toggle a Purple modal, or leave as false for White\n * @param {boolean?} options.textLeft - Toggle to align modal text to the left, or leave as false for center\n * @param {boolean?} options.noPadding - Toggle zero padding, or leave as false for default padding\n * @param {number?} options.maxHeight - An optional modal Max Height, omit for default modal max\n * @returns {Promise}\n */\nexport async function confirmPopup({\n title,\n html,\n resolvePromise,\n hideConfirm,\n purpleModal,\n textLeft,\n noPadding,\n maxHeight,\n}) {\n // If there's a title provided: display the header and text\n doms.domConfirmModalHeader.style.display = title ? 'block' : 'none';\n doms.domConfirmModalTitle.innerHTML = title || '';\n\n // If there's a promise to resolve, don't display buttons; the modal visibility will be controlled by the promise (f.e: a 'pls wait' screen)\n doms.domConfirmModalButtons.style.setProperty(\n 'display',\n resolvePromise ? 'none' : 'block',\n resolvePromise ? 'important' : undefined\n );\n $('#confirmModal').modal(resolvePromise ? 'show' : { keyboard: false });\n\n // Show or hide the confirm button, and replace 'Cancel' with 'Close'\n doms.domConfirmModalConfirmButton.style.display = hideConfirm ? 'none' : '';\n doms.domConfirmModalCancelButton.innerText = hideConfirm\n ? translation.popupClose\n : translation.popupCancel;\n\n // Set content display\n doms.domConfirmModalContent.innerHTML = html;\n\n // Set text align to left\n if (textLeft) {\n doms.domConfirmModalContent.classList.remove('center-text');\n } else {\n doms.domConfirmModalContent.classList.add('center-text');\n }\n\n // Use the purple modal\n if (purpleModal) {\n doms.domConfirmModalMain.classList.add('exportKeysModalColor');\n } else {\n doms.domConfirmModalMain.classList.remove('exportKeysModalColor');\n }\n\n // Remove padding\n if (noPadding) {\n doms.domConfirmModalContent.classList.add('px-0');\n doms.domConfirmModalContent.classList.add('pb-0');\n } else {\n doms.domConfirmModalContent.classList.remove('px-0');\n doms.domConfirmModalContent.classList.remove('pb-0');\n }\n\n // Set max-height (removed at `.finally` context)\n if (maxHeight)\n doms.domConfirmModalDialog.classList.add(`max-w-${maxHeight}`);\n\n // If there's an input in the prompt, focus the cursor upon it\n for (const domElement of doms.domConfirmModalContent.children) {\n if (domElement.type === 'text' || domElement.type === 'password') {\n domElement.focus();\n break;\n }\n }\n\n // Wait for the promise to resolve OR create a new one which resolves upon a modal button click\n resolvePromise =\n resolvePromise ||\n new Promise((res, _) => {\n doms.domConfirmModalConfirmButton.onclick = () => {\n res(true);\n };\n doms.domConfirmModalCancelButton.onclick = () => {\n res(false);\n };\n });\n try {\n return await resolvePromise;\n } finally {\n // We want to hide the modal even if an exception occurs\n $('#confirmModal').modal('hide');\n\n // Reset any modal settings\n doms.domConfirmModalDialog.classList.remove(`max-w-${maxHeight}`);\n }\n}\n\n// Generates and sets a QRCode image from a string and dom element\nexport function createQR(strData = '', domImg, size = 4) {\n // QRCode class consists of 'typeNumber' & 'errorCorrectionLevel'\n const cQR = qrcode(size, 'L');\n cQR.addData(strData);\n cQR.make();\n domImg.innerHTML = cQR.createImgTag(2, 2);\n domImg.firstChild.style.borderRadius = '8px';\n}\n\n/**\n * Prompt image selection, and return base64 of an image file.\n * @returns {Promise} The base64 string of the selected image file.\n */\nexport async function getImageFile() {\n return new Promise((resolve) => {\n let input = document.createElement('input');\n input.type = 'file';\n input.accept = 'image/*';\n input.onchange = (e) => {\n let file = e.target.files[0];\n let reader = new FileReader();\n reader.onloadend = () => resolve(reader.result);\n reader.readAsDataURL(file);\n };\n input.click();\n });\n}\n\n/**\n * A quick check to see if an address is a Standard (P2PKH) address\n * @param {string} strAddress - The address to check\n * @returns {boolean} - `true` if a Standard address, `false` if not\n */\nexport function isStandardAddress(strAddress) {\n return (\n strAddress.length === 34 &&\n cChainParams.current.PUBKEY_PREFIX.includes(strAddress[0])\n );\n}\n\n/**\n * A quick check to see if a string is an XPub key\n * @param {string} strXPub - The XPub to check\n * @returns {boolean} - `true` if a valid formatted XPub, `false` if not\n */\nexport function isXPub(strXPub) {\n if (!strXPub.startsWith('xpub')) return false;\n\n // Attempt to Base58 decode the XPub\n try {\n // Slice away the `xpub` prefix and decode\n const decoded = bs58.decode(strXPub.slice(4));\n\n // Then verify the final length too\n return decoded.length === 78;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Attempt to safely parse a BIP21 Payment Request\n * @param {string} strReq - BIP21 Payment Request string\n * @returns {object | false}\n */\nexport function parseBIP21Request(strReq) {\n // Format should match: pivx:addr[?amount=x&label=x]\n if (!strReq.includes(BIP21_PREFIX + ':')) return false;\n\n const [addressPart, optionsPart] = strReq.includes('?')\n ? strReq.split('?')\n : [strReq, false];\n const strAddress = addressPart.substring(BIP21_PREFIX.length + 1); // remove 'pivx:' prefix\n let cOptions = {};\n\n // Ensure the address is valid\n if (\n // Standard address\n !isStandardAddress(strAddress) &&\n // Shield address\n !isValidBech32(strAddress).valid\n ) {\n return false;\n }\n\n if (optionsPart) {\n cOptions = Object.fromEntries(\n optionsPart\n .split('&')\n .map((opt) => opt.split('=').map(decodeURIComponent))\n );\n }\n\n return { address: strAddress, options: cOptions };\n}\n\n/**\n * @typedef {object} Bech32Check\n * @property {boolean} valid - If the string is a valid bech32 address\n * @property {object} res - The results of the bech32 decoding\n */\n\n/**\n * A safe bech32 wrapper for quickly checking if an address is valid\n * @param {string} str - Bech32 Address\n * @returns {Bech32Check} - Both the validity and decoding results\n */\nexport function isValidBech32(str) {\n try {\n return { valid: true, res: bech32.decode(str) };\n } catch (e) {\n return { valid: false, res: e };\n }\n}\n\n/**\n * Generate an encoded private key for masternodes\n */\nexport function generateMasternodePrivkey() {\n // Prefix the network byte with the private key (32 random bytes)\n const data = [cChainParams.current.SECRET_KEY, ...getSafeRand(32)];\n\n // Compute and concatenate the checksum, then encode the private key as Base58\n return bs58.encode([...data, ...dSHA256(data).slice(0, 4)]);\n}\n\nexport function sanitizeHTML(text) {\n const element = document.createElement('div');\n element.innerText = text;\n return element.innerHTML;\n}\n\n/**\n * \"Beautifies\" a number with HTML, by displaying decimals in a lower opacity\n * @param {string} strNumber - The number in String form to beautify\n * @param {string?} strDecFontSize - The optional font size to display decimals in\n * @returns {string} - A HTML string with beautified number handling\n */\nexport function beautifyNumber(strNumber, strDecFontSize = '') {\n if (typeof strNumber === 'number') strNumber = strNumber.toString();\n\n // Only run this for numbers with decimals\n if (!strNumber.includes('.')) return strNumber;\n\n // Split the number in to Full and Decimal parts\n const arrNumParts = strNumber.split('.');\n\n // Return a HTML that renders the decimal in a lower opacity\n const strFontSize = strDecFontSize ? 'font-size: ' + strDecFontSize : '';\n return `${arrNumParts[0]}.${arrNumParts[1]}`;\n}\n\n/**\n * Check if a string is valid Base64 encoding\n * @param {string} str - String to check\n * @returns {boolean}\n */\nexport function isBase64(str) {\n const base64Regex = /^[A-Za-z0-9+/=]+$/;\n\n // Check if the string contains only Base64 characters:\n if (!base64Regex.test(str)) {\n return false;\n }\n\n // Check if the length is a multiple of 4 (required for Base64):\n if (str.length % 4 !== 0) {\n return false;\n }\n\n // Try decoding the Base64 string to check for errors:\n try {\n atob(str);\n } catch (e) {\n return false;\n }\n\n // The string is likely Base64-encoded:\n return true;\n}\n\n/**\n * Checks if two values are of the same type.\n *\n * @param {any} a - The first value.\n * @param {any} b - The second value.\n * @returns {boolean} - `true` if the values are of the same type, `false` if not or if there was an error comparing.\n */\nexport function isSameType(a, b) {\n try {\n if (a === null || b === null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a === 'object')\n return Object.getPrototypeOf(a) === Object.getPrototypeOf(b);\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Checks if a value is 'empty'.\n *\n * @param {any} val - The value to check.\n * @returns {boolean} - `true` if the value is 'empty', `false` otherwise.\n * ---\n * Values **considered 'empty'**: `null`, `undefined`, empty strings, empty arrays, empty objects.\n *\n * Values **NOT considered 'empty'**: Any non-nullish primitive value: numbers (including `0` and `NaN`), `true`, `false`, `Symbol()`, `BigInt()`.\n */\nexport function isEmpty(val) {\n return (\n val == null ||\n val === '' ||\n (Array.isArray(val) && val.length === 0) ||\n (typeof val === 'object' && Object.keys(val).length === 0)\n );\n}\n\n/**\n * An artificial sleep function to pause code execution\n *\n * @param {Number} ms - The milliseconds to sleep\n *\n * @example\n * // Pause an asynchronous script for 1 second\n * await sleep(1000);\n */\nexport function sleep(ms) {\n return new Promise((res, _) => setTimeout(res, ms));\n}\n","export const OP = {\n // push value\n 0: 0x00,\n FALSE: 0x00, // ALIAS FOR: 0\n PUSHDATA1: 0x4c,\n PUSHDATA2: 0x4d,\n PUSHDATA4: 0x4e,\n '1NEGATE': 0x4f,\n RESERVED: 0x50,\n 1: 0x51,\n TRUE: 0x51, // ALIAS FOR: 1\n 2: 0x52,\n 3: 0x53,\n 4: 0x54,\n 5: 0x55,\n 6: 0x56,\n 7: 0x57,\n 8: 0x58,\n 9: 0x59,\n 10: 0x5a,\n 11: 0x5b,\n 12: 0x5c,\n 13: 0x5d,\n 14: 0x5e,\n 15: 0x5f,\n 16: 0x60,\n\n // control\n NOP: 0x61,\n VER: 0x62,\n IF: 0x63,\n NOTIF: 0x64,\n VERIF: 0x65,\n VERNOTIF: 0x66,\n ELSE: 0x67,\n ENDIF: 0x68,\n VERIFY: 0x69,\n RETURN: 0x6a,\n\n // stack ops\n TOALTSTACK: 0x6b,\n FROMALTSTACK: 0x6c,\n '2DROP': 0x6d,\n '2DUP': 0x6e,\n '3DUP': 0x6f,\n '2OVER': 0x70,\n '2ROT': 0x71,\n '2SWAP': 0x72,\n IFDUP: 0x73,\n DEPTH: 0x74,\n DROP: 0x75,\n DUP: 0x76,\n NIP: 0x77,\n OVER: 0x78,\n PICK: 0x79,\n ROLL: 0x7a,\n ROT: 0x7b,\n SWAP: 0x7c,\n TUCK: 0x7d,\n\n // splice ops\n CAT: 0x7e,\n SUBSTR: 0x7f,\n LEFT: 0x80,\n RIGHT: 0x81,\n SIZE: 0x82,\n\n // bit logic\n INVERT: 0x83,\n AND: 0x84,\n OR: 0x85,\n XOR: 0x86,\n EQUAL: 0x87,\n EQUALVERIFY: 0x88,\n RESERVED1: 0x89,\n RESERVED2: 0x8a,\n\n // numeric\n '1ADD': 0x8b,\n '1SUB': 0x8c,\n '2MUL': 0x8d,\n '2DIV': 0x8e,\n NEGATE: 0x8f,\n ABS: 0x90,\n NOT: 0x91,\n '0NOTEQUAL': 0x92,\n\n ADD: 0x93,\n SUB: 0x94,\n MUL: 0x95,\n DIV: 0x96,\n MOD: 0x97,\n LSHIFT: 0x98,\n RSHIFT: 0x99,\n\n BOOLAND: 0x9a,\n BOOLOR: 0x9b,\n NUMEQUAL: 0x9c,\n NUMEQUALVERIFY: 0x9d,\n NUMNOTEQUAL: 0x9e,\n LESSTHAN: 0x9f,\n GREATERTHAN: 0xa0,\n LESSTHANOREQUAL: 0xa1,\n GREATERTHANOREQUAL: 0xa2,\n MIN: 0xa3,\n MAX: 0xa4,\n\n WITHIN: 0xa5,\n\n // crypto\n RIPEMD160: 0xa6,\n SHA1: 0xa7,\n SHA256: 0xa8,\n HASH160: 0xa9,\n HASH256: 0xaa,\n CODESEPARATOR: 0xab,\n CHECKSIG: 0xac,\n CHECKSIGVERIFY: 0xad,\n CHECKMULTISIG: 0xae,\n CHECKMULTISIGVERIFY: 0xaf,\n\n // expansion\n NOP1: 0xb0,\n NOP2: 0xb1,\n CHECKLOCKTIMEVERIFY: 0xb1, // ALIAS FOR: NOP2\n NOP3: 0xb2,\n NOP4: 0xb3,\n NOP5: 0xb4,\n NOP6: 0xb5,\n NOP7: 0xb6,\n NOP8: 0xb7,\n NOP9: 0xb8,\n NOP10: 0xb9,\n\n // zerocoin\n ZEROCOINMINT: 0xc1,\n ZEROCOINSPEND: 0xc2,\n ZEROCOINPUBLICSPEND: 0xc3,\n\n // cold staking\n CHECKCOLDSTAKEVERIFY_LOF: 0xd1, // last output free for masternode/budget payments\n CHECKCOLDSTAKEVERIFY: 0xd2,\n\n INVALIDOPCODE: 0xff,\n};\nObject.freeze(OP);\n\nexport function getScriptForBurn(data) {\n let cScript = [];\n // Check if we're fitting any data into the TX\n if (typeof data === 'string' && data.length > 0) {\n let bData = new TextEncoder().encode(data);\n cScript.push(OP['RETURN']);\n cScript.push(OP['PUSHDATA1']);\n // Append the byte array length\n cScript.push(bData.length);\n // Convert from uint8 to array and append the byte array\n cScript = cScript.concat(Array.prototype.slice.call(bData));\n } else {\n // Empty data, create a simple RETURN script\n cScript.push(OP['RETURN']);\n }\n // Return the burn script\n return cScript;\n}\n","import { openDB, IDBPDatabase } from 'idb';\nimport Masternode from './masternode.js';\nimport { Settings } from './settings.js';\nimport { cChainParams } from './chain_params.js';\nimport {\n confirmPopup,\n sanitizeHTML,\n createAlert,\n isSameType,\n isEmpty,\n} from './misc.js';\nimport { PromoWallet } from './promos.js';\nimport { ALERTS, translation } from './i18n.js';\nimport { Account } from './accounts.js';\n\n/** The current version of the DB - increasing this will prompt the Upgrade process for clients with an older version */\nexport const DB_VERSION = 2;\n\n/**\n *\n */\nexport class Database {\n /**\n * Current Database Version.\n * Version 1 = Add index DB (PR #[FILL])\n * @type{Number}\n */\n static version = 1;\n\n /**\n * @type{IDBPDatabase}\n */\n #db;\n\n constructor({ db }) {\n this.#db = db;\n }\n\n close() {\n this.#db.close();\n this.#db = null;\n }\n\n /**\n * Add masternode to the database\n * @param {Masternode} masternode\n * @param {Masterkey} _masterKey - Masterkey associated to the masternode. Currently unused\n */\n async addMasternode(masternode, _masterKey) {\n const store = this.#db\n .transaction('masternodes', 'readwrite')\n .objectStore('masternodes');\n // For now the key is 'masternode' since we don't support multiple masternodes\n await store.put(masternode, 'masternode');\n }\n /**\n * Removes a masternode\n * @param {Masterkey} _masterKey - Masterkey associated to the masternode. Currently unused\n */\n async removeMasternode(_masterKey) {\n const store = this.#db\n .transaction('masternodes', 'readwrite')\n .objectStore('masternodes');\n await store.delete('masternode');\n }\n\n /**\n * Add Promo Code to the database for tracking and management\n * @param {PromoWallet} promo\n */\n async addPromo(promo) {\n const store = this.#db\n .transaction('promos', 'readwrite')\n .objectStore('promos');\n // The plaintext code is our key, since codes are unique and deterministic anyway\n await store.put(promo, promo.code);\n }\n /**\n * Removes a Promo Code from the Promo management system\n * @param {string} promo - the promo code to remove\n */\n async removePromo(promo) {\n const store = this.#db\n .transaction('promos', 'readwrite')\n .objectStore('promos');\n await store.delete(promo);\n }\n\n /**\n * Adds an account to the database\n *\n * This will also apply missing Account keys from the Account class automatically, and check high-level type safety.\n * @param {Account} account - The Account to add\n */\n async addAccount(account) {\n // Critical: Ensure the input is an Account instance\n if (!(account instanceof Account)) {\n console.error(\n '---- addAccount() called with invalid input, input dump below ----'\n );\n console.error(account);\n console.error('---- end of account dump ----');\n createAlert(\n 'warning',\n 'Account Creation Error
Logs were dumped in your Browser Console
Please submit these privately to PIVX Labs Developers!'\n );\n return false;\n }\n\n // Create an empty DB Account\n const cDBAccount = new Account();\n\n // We'll overlay the `account` keys atop the `DB Account` keys:\n // Note: Since the Account constructor defaults all properties to type-safe defaults, we can already assume `cDBAccount` is safe.\n // Note: Since `addAccount` could be called with *anything*, we must apply the same type-safety on it's input.\n for (const strKey of Object.keys(cDBAccount)) {\n // Ensure the Type is correct for the Key against the Account class\n if (!isSameType(account[strKey], cDBAccount[strKey])) {\n console.error(\n 'DB: addAccount() key \"' +\n strKey +\n '\" does NOT match the correct class type, likely data mismatch, please report!'\n );\n continue;\n }\n\n // Overlay the 'new' keys on top of the DB keys\n cDBAccount[strKey] = account[strKey];\n }\n\n const store = this.#db\n .transaction('accounts', 'readwrite')\n .objectStore('accounts');\n\n // Check this account isn't already added (by pubkey once multi-account)\n if (await store.get('account'))\n return console.error(\n 'DB: Ran addAccount() when account already exists!'\n );\n\n // When the account system is going to be added, the key is gonna be the publicKey\n await store.put(cDBAccount, 'account');\n }\n\n /**\n * Update specified keys for an Account in the DB.\n *\n * This will also apply new Account keys from MPW updates automatically, and check high-level type safety.\n *\n * ---\n *\n * To allow \"deleting/clearing/resetting\" keys, for example, when removing Proposals or Contacts, toggle `allowDeletion`.\n *\n * **Do NOT toggle unless otherwise necessary**, to avoid overwriting keys from code errors or misuse.\n * @param {Account} account - The Account to update, with new data inside\n * @param {boolean} allowDeletion - Allow setting keys to an \"empty\" state (`\"\"`, `[]`, `{}`)\n */\n async updateAccount(account, allowDeletion = false) {\n // Critical: Ensure the input is an Account instance\n if (!(account instanceof Account)) {\n console.error(\n '---- updateAccount() called with invalid input, input dump below ----'\n );\n console.error(account);\n console.error('---- end of account dump ----');\n createAlert(\n 'warning',\n 'DB Update Error
Your wallet is safe, logs were dumped in your Browser Console
Please submit these privately to PIVX Labs Developers!'\n );\n return false;\n }\n\n // Fetch the DB account\n const cDBAccount = await this.getAccount();\n\n // If none exists; we should throw an error, as there's no reason for MPW to call `updateAccount` before an account was added using `addAccount`\n // Note: This is mainly to force \"good standards\" in which we don't lazily use `updateAccount` to create NEW accounts.\n if (!cDBAccount) {\n console.error(\n '---- updateAccount() called without an account existing, input dump below ----'\n );\n console.error(account);\n console.error('---- end of input dump ----');\n createAlert(\n 'warning',\n 'DB Update Error
Logs were dumped in your Browser Console
Please submit these privately to PIVX Labs Developers!'\n );\n return false;\n }\n\n // We'll overlay the `account` keys atop the `DB Account` keys:\n // Note: Since `getAccount` already checks type-safety, we can already assume `cDBAccount` is safe.\n // Note: Since `updateAccount` could be called with *anything*, we must apply the same type-safety on it's input.\n for (const strKey of Object.keys(cDBAccount)) {\n // Ensure the Type is correct for the Key against the Account class\n if (!isSameType(account[strKey], cDBAccount[strKey])) {\n console.error(\n 'DB: updateAccount() key \"' +\n strKey +\n '\" does NOT match the correct class type, likely data mismatch, please report!'\n );\n continue;\n }\n\n // Ensure the 'updated' key (which may not exist) is NOT a default or EMPTY value\n // Note: this can be overriden manually when erasing data such as Contacts, Local Proposals, etc.\n if (!allowDeletion && isEmpty(account[strKey])) continue;\n\n // Overlay the 'new' keys on top of the DB keys\n cDBAccount[strKey] = account[strKey];\n }\n\n const store = this.#db\n .transaction('accounts', 'readwrite')\n .objectStore('accounts');\n // When the account system is going to be added, the key is gonna be the publicKey\n await store.put(cDBAccount, 'account');\n }\n\n /**\n * Removes an account from the database\n * @param {Object} o\n * @param {String} o.publicKey - Public key associated to the account.\n */\n async removeAccount({ publicKey }) {\n const store = this.#db\n .transaction('accounts', 'readwrite')\n .objectStore('accounts');\n // When the account system is going to be added, the key is gonna be the publicKey\n await store.delete('account');\n }\n\n /**\n * Gets an account from the database.\n *\n * This also will apply new keys from MPW updates automatically, and check high-level type safety.\n * @returns {Promise}\n */\n async getAccount() {\n const store = this.#db\n .transaction('accounts', 'readonly')\n .objectStore('accounts');\n const cDBAccount = await store.get('account');\n\n // If there's no DB Account, we'll return null early\n if (!cDBAccount) return null;\n\n // We'll generate an Account Class for up-to-date keys, then layer the 'new' type-checked properties on it one-by-one\n const cAccount = new Account();\n for (const strKey of Object.keys(cAccount)) {\n // Ensure the Type is correct for the Key against the Account class (with instanceof to also check Class validity)\n if (!isSameType(cDBAccount[strKey], cAccount[strKey])) {\n console.error(\n 'DB: getAccount() key \"' +\n strKey +\n '\" does NOT match the correct class type, likely bad data saved, please report!'\n );\n continue;\n }\n\n // Overlay the 'DB' keys on top of the Class Instance keys\n cAccount[strKey] = cDBAccount[strKey];\n }\n\n // Return the Account Class\n return cAccount;\n }\n\n /**\n * @returns {Promise} the masternode stored in the db\n */\n async getMasternode(_masterKey) {\n const store = this.#db\n .transaction('masternodes', 'readonly')\n .objectStore('masternodes');\n return new Masternode(await store.get('masternode'));\n }\n\n /**\n * @returns {Promise>} all Promo Codes stored in the db\n */\n async getAllPromos() {\n const store = this.#db\n .transaction('promos', 'readonly')\n .objectStore('promos');\n // Convert all promo objects in to their Class and return them as a new array\n return (await store.getAll()).map((promo) => new PromoWallet(promo));\n }\n\n /**\n * @returns {Promise}\n */\n async getSettings() {\n const store = this.#db\n .transaction('settings', 'readonly')\n .objectStore('settings');\n return new Settings(await store.get('settings'));\n }\n\n /**\n * @param {Settings} settings - settings to use\n * @returns {Promise}\n */\n async setSettings(settings) {\n const oldSettings = await this.getSettings();\n const store = this.#db\n .transaction('settings', 'readwrite')\n .objectStore('settings');\n await store.put(\n {\n ...oldSettings,\n ...settings,\n },\n 'settings'\n );\n }\n\n /**\n * Migrates from local storage\n * @param {IDBPDatabase} db\n */\n async #migrateLocalStorage() {\n if (localStorage.length === 0) return;\n const settings = new Settings({\n analytics: localStorage.analytics,\n explorer: localStorage.explorer,\n node: localStorage.node,\n translation: localStorage.translation,\n displayCurrency: localStorage.displayCurrency,\n });\n await this.setSettings(settings);\n\n if (localStorage.masternode) {\n try {\n const masternode = JSON.parse(localStorage.masternode);\n await this.addMasternode(masternode);\n } catch (e) {\n console.error(e);\n createAlert('warning', ALERTS.MIGRATION_MASTERNODE_FAILURE);\n }\n }\n\n if (localStorage.encwif || localStorage.publicKey) {\n try {\n const localProposals = JSON.parse(\n localStorage.localProposals || '[]'\n );\n\n // Update and format the old Account data\n const cAccount = new Account({\n publicKey: localStorage.publicKey,\n encWif: localStorage.encwif,\n localProposals: localProposals,\n });\n\n // Migrate the old Account data to the new DB\n await this.addAccount(cAccount);\n } catch (e) {\n console.error(e);\n createAlert('warning', ALERTS.MIGRATION_ACCOUNT_FAILURE);\n if (localStorage.encwif) {\n await confirmPopup({\n title: translation.MIGRATION_ACCOUNT_FAILURE_TITLE,\n html: `${\n translation.MIGRATION_ACCOUNT_FAILURE_HTML\n } ${sanitizeHTML(\n localStorage.encwif\n )} `,\n });\n }\n }\n }\n }\n\n static async create(name) {\n let migrate = false;\n const database = new Database({ db: null });\n const db = await openDB(`MPW-${name}`, DB_VERSION, {\n upgrade: (db, oldVersion) => {\n console.log(\n 'DB: Upgrading from ' + oldVersion + ' to ' + DB_VERSION\n );\n if (oldVersion == 0) {\n db.createObjectStore('masternodes');\n db.createObjectStore('accounts');\n db.createObjectStore('settings');\n migrate = true;\n }\n\n // The introduction of PIVXPromos (safely added during {\n // Another instance is waiting to upgrade, and we're preventing it\n // Close the database and refresh the page\n // (This would only happen if the user opened another window after MPW got an update)\n database.close();\n alert('New update received!');\n window.location.reload();\n },\n });\n database.#db = db;\n if (migrate) {\n database.#migrateLocalStorage();\n }\n return database;\n }\n\n /**\n * Map name->instnace\n * @type{Map}\n */\n static #instances = new Map();\n\n /**\n * @return {Promise} the default database instance\n */\n static async getInstance() {\n const name = cChainParams.current.name;\n const instance = this.#instances.get(name);\n if (!instance || !instance.#db) {\n this.#instances.set(name, await Database.create(name));\n }\n\n return this.#instances.get(name);\n }\n}\n","import { en_translation } from '../locale/en/translation.js';\nimport { pt_br_translation } from '../locale/pt-br/translation.js';\nimport { pt_pt_translation } from '../locale/pt-pt/translation.js';\nimport { ph_translation } from '../locale/ph/translation.js';\nimport { uwu_translation } from '../locale/uwu/translation.js';\nimport { fr_translation } from '../locale/fr/translation.js';\nimport { de_translation } from '../locale/de/translation.js';\nimport { Database } from './database.js';\nimport { fillAnalyticSelect, setTranslation } from './settings.js';\nimport { renderActivityGUI, updateEncryptionGUI } from './global.js';\nimport { masterKey } from './wallet.js';\nimport { getNetwork } from './network.js';\nimport { cReceiveType, guiToggleReceiveType } from './contacts-book.js';\n\nexport const ALERTS = {};\nexport let translation = {};\n\n// TRANSLATION\n//Create an object of objects filled with all the translations\nexport const translatableLanguages = {\n en: en_translation,\n uwu: uwu_translation,\n 'pt-pt': pt_pt_translation,\n 'pt-br': pt_br_translation,\n ph: ph_translation,\n fr: fr_translation,\n de: de_translation,\n};\n\n/**\n * Takes the language name and sets the translation settings based on the language file\n * @param {string} langName\n */\nexport function switchTranslation(langName) {\n if (arrActiveLangs.find((lang) => lang.code === langName)) {\n // Load every 'active' key of the language, otherwise, we'll default the key to the EN file\n const arrNewLang = translatableLanguages[langName];\n for (const strKey of Object.keys(arrNewLang)) {\n // Skip empty and/or missing i18n keys, defaulting them to EN\n if (!arrNewLang[strKey]) {\n translation[strKey] = translatableLanguages.en[strKey];\n continue;\n }\n\n // Apply the new i18n value to our runtime i18n sheet\n translation[strKey] = arrNewLang[strKey];\n }\n\n // Translate static`data-i18n` tags\n translateStaticHTML(translation);\n\n // Translate any dynamic elements necessary\n const cNet = getNetwork();\n if (masterKey && cNet) {\n updateEncryptionGUI();\n renderActivityGUI(cNet.arrTxHistory);\n }\n loadAlerts();\n fillAnalyticSelect();\n if (masterKey) {\n guiToggleReceiveType(cReceiveType);\n }\n return true;\n } else {\n console.log(\n 'i18n: The language (' +\n langName +\n \") is not supported yet, if you'd like to contribute translations (for rewards!) contact us on GitHub or Discord!\"\n );\n translation = translatableLanguages.en_translation;\n return false;\n }\n}\n\n/**\n * Takes an i18n string that includes `{x}` and replaces that based on what is in the array of objects\n * @param {string} message\n * @param {Array} variables\n * @returns a string with the variables implemented in the string\n *\n * @example\n * //returns \"test this\"\n * tr(\"test {x}\" [x: \"this\"])\n */\nexport function tr(message, variables) {\n variables.forEach((element) => {\n message = message.replaceAll(\n '{' + Object.keys(element)[0] + '}',\n Object.values(element)[0]\n );\n });\n return message;\n}\n\n/**\n * Translates all static HTML based on the `data-i18n` tag\n * @param {Array} i18nLangs\n *\n */\nexport function translateStaticHTML(i18nLangs) {\n if (!i18nLangs) return;\n\n document.querySelectorAll('[data-i18n]').forEach(function (element) {\n if (!i18nLangs[element.dataset.i18n]) return;\n\n if (element.dataset.i18n_target) {\n element[element.dataset.i18n_target] =\n i18nLangs[element.dataset.i18n];\n } else {\n switch (element.tagName.toLowerCase()) {\n case 'input':\n case 'textarea':\n element.placeholder = i18nLangs[element.dataset.i18n];\n break;\n default:\n element.innerHTML = i18nLangs[element.dataset.i18n];\n break;\n }\n }\n });\n loadAlerts();\n}\n\n/**\n * Translates the alerts by loading the data into the ALERTS object\n */\nexport function loadAlerts() {\n // Alerts are designated by a special 'ALERTS' entry in each translation file\n let fFoundAlerts = false;\n for (const [alert_key, alert_translation] of Object.entries(translation)) {\n if (fFoundAlerts) {\n ALERTS[alert_key] = alert_translation;\n }\n // Skip all entries until we find the ALERTS flag\n if (alert_key === 'ALERTS') fFoundAlerts = true;\n }\n}\nfunction parseUserAgentLang(strUA, arrLangsWithSubset) {\n if (arrLangsWithSubset.some((strLang) => strUA.includes(strLang))) {\n // Split the lang in to 'primary' and 'subset', only use the primary lang\n return strUA.substring(0, 2);\n }\n // Otherwise, just use the full language spec\n return strUA;\n}\n\n// When adding a lang remember to add it to the object translatableLanguages as well as here.\nexport const arrActiveLangs = [\n { code: 'en', emoji: '🇬🇧' },\n { code: 'fr', emoji: '🇫🇷' },\n { code: 'de', emoji: '🇩🇪' },\n { code: 'pt-pt', emoji: '🇵🇹' },\n { code: 'pt-br', emoji: '🇧🇷' },\n { code: 'ph', emoji: '🇵🇭' },\n { code: 'uwu', emoji: '🐈' },\n];\n\nexport async function start() {\n // We use this function to parse the UA lang in a safer way: for example, there's multiple `en` definitions\n // ... but we shouldn't duplicate the language files, we can instead cut the affix (US, GB) and simply use 'en'.\n // ... This logic may apply to other languages with such subsets as well, so take care of them here!\n const arrLangsWithSubset = ['en', 'fr', 'de'];\n\n const localeLang =\n window?.navigator?.userLanguage || window?.navigator?.language;\n const strLang = localeLang\n ? parseUserAgentLang(localeLang.toLowerCase(), arrLangsWithSubset)\n : undefined;\n\n // When removing you do not have to remove from translatableLanguages\n const database = await Database.getInstance();\n const { translation: localTranslation } = await database.getSettings();\n\n // Check if set in local storage\n if (localTranslation !== '') {\n setTranslation(localTranslation);\n } else {\n // Check if we support the user's browser locale\n if (arrActiveLangs.find((lang) => lang.code === strLang)) {\n setTranslation(strLang);\n } else {\n // Default to EN if the locale isn't supported yet\n console.log(\n 'i18n: Your language (' +\n strLang +\n \") is not supported yet, if you'd like to contribute translations (for rewards!) contact us on GitHub or Discord!\"\n );\n setTranslation('en');\n }\n }\n translateStaticHTML(translation);\n}\n","import { EventEmitter } from 'events';\n\nconst eventEmitter = new EventEmitter();\n\n/**\n * Get the application wide event emitter.\n * @returns {EventEmitter}\n */\nexport function getEventEmitter() {\n return eventEmitter;\n}\n","import { getNetwork } from './network.js';\nimport { getBalance, isMasternodeUTXO, getStakingBalance } from './global.js';\nimport { sleep } from './misc.js';\nimport { debug } from './settings.js';\nimport { getEventEmitter } from './event_bus.js';\n\n/**\n * @typedef {Object} cIn - An input of a Tx\n * @property {string} txid - The transaction ID\n * @property {number} vout - The output index\n */\n\n/** An Unspent Transaction Output, used as Inputs of future transactions */\nexport class UTXO {\n /**\n * @param {Object} UTXO\n * @param {String} UTXO.id - Transaction ID\n * @param {String} UTXO.path - If applicable, the HD Path of the owning address\n * @param {Number} UTXO.sats - Satoshi value in this UTXO\n * @param {String} UTXO.script - HEX encoded spending script\n * @param {Array?} UTXO.vin - The inputs of the transaction, if any\n * @param {Number} UTXO.vout - Output position of this transaction\n * @param {Number} UTXO.height - Block height of the UTXO\n * @param {Number} UTXO.status - UTXO status enum state\n * @param {boolean} UTXO.isDelegate - Whether the UTXO is a cold stake delegation\n * @param {boolean} UTXO.isReward - Whether the UTXO is a reward\n */\n constructor({\n id,\n path,\n sats,\n script,\n vin = [],\n vout,\n height,\n status,\n isDelegate = false,\n isReward = false,\n } = {}) {\n /** Transaction ID\n * @type {String} */\n this.id = id;\n\n /** HD Path of the owning address\n * @type {String} */\n this.path = path;\n\n /** Satoshi value in this UTXO\n * @type {Number} */\n this.sats = sats;\n\n /** HEX encoded spending script\n * @type {String} */\n this.script = script;\n\n /** The inputs of the transaction, if any\n * @type {Array} */\n this.vin = vin;\n\n /** Output position of this transaction\n * @type {Number} */\n this.vout = vout;\n\n /** Block height of the UTXO\n * @type {Number} */\n this.height = height;\n\n /** UTXO status enum state\n * @type {Number} */\n this.status = status;\n\n /** Whether it's a delegation UTXO\n * @type {boolean} */\n this.isDelegate = isDelegate;\n\n /** Whether it's a reward UTXO\n * @type {boolean} */\n this.isReward = isReward;\n }\n\n /**\n * Check for equality between this UTXO and another UTXO\n * @param {UTXO} cUTXO - UTXO to compare against\n * @returns {Boolean} `true` if equal, `false` if unequal\n */\n equalsUTXO(cUTXO) {\n return (\n this.id === cUTXO.id &&\n this.vout === cUTXO.vout &&\n this.status === cUTXO.status\n );\n }\n}\n\n/** A Mempool instance, stores and handles UTXO data for the wallet */\nexport class Mempool {\n constructor() {\n /**\n * An array of all known UTXOs\n * @type {Array}\n */\n this.UTXOs = [];\n this.subscribeToNetwork();\n }\n\n /** The CONFIRMED state (UTXO is spendable) */\n static CONFIRMED = 0;\n\n /** The REMOVED state (UTXO was spent and will be removed soon) */\n static REMOVED = 1;\n\n /** The PENDING state (standard UTXO is in mempool, pending confirmation) */\n static PENDING = 2;\n\n /**\n * Fetch a UTXO by ID and Index\n * @param {string} id - Transaction ID of the UTXO\n * @param {number} out - Output position of the UTXO\n */\n getUTXO(id, out) {\n return this.UTXOs.find(\n (cUTXO) => cUTXO.id === id && cUTXO.vout === out\n );\n }\n\n /**\n * Remove a UTXO after a set amount of time\n * @param {Number} nBlocks - Estimated blocks to wait\n * @param {UTXO} cUTXO - UTXO to remove\n */\n async removeWithDelay(nBlocks, cUTXO) {\n await sleep(nBlocks * 60 * 1000);\n this.removeUTXO(cUTXO);\n }\n\n /**\n * Check if an exact UTXO match can be found in our wallet\n * @param {Object} UTXO\n * @param {String} UTXO.id - Transaction ID\n * @param {Number} UTXO.vout - Output position of this transaction\n * @param {Number} [UTXO.status] - UTXO status enum state. If it's undefined, it will ignore it.\n * @returns {Boolean} `true` or `false`\n */\n isAlreadyStored({ id, vout, status }) {\n return this.UTXOs.some(\n (cUTXO) =>\n cUTXO.id === id &&\n cUTXO.vout === vout &&\n (!status || cUTXO.status === status)\n );\n }\n\n /**\n * Fetches an array of UTXOs filtered by their state\n * @param {Number} nState - Specific UTXO state\n * @returns {Array} `array` - An array of UTXOs\n */\n getUTXOsByState(nState) {\n return this.UTXOs.filter((cUTXO) => cUTXO.status === nState);\n }\n\n /**\n * Removes a UTXO from a specific state\n * @param {UTXO} cNewUTXO - Pending UTXO to remove\n * @param {Number} nState - Specific state of this UTXO to search for\n */\n removeFromState(cNewUTXO, nState) {\n const arrPendingUTXOs = this.getUTXOsByState(nState);\n // Loop each pending UTXO\n for (const cUTXO of arrPendingUTXOs) {\n // Search for matching ID + output number\n if (cUTXO.id === cNewUTXO.id && cUTXO.vout === cNewUTXO.vout) {\n // Nuke it from orbit\n this.removeUTXO(cUTXO);\n break;\n }\n }\n }\n\n /**\n * Add a new UTXO to the wallet\n * @param {UTXO} UTXO\n */\n addUTXO({\n id,\n path,\n sats,\n script,\n vin,\n vout,\n height,\n status,\n isDelegate,\n isReward,\n }) {\n const newUTXO = new UTXO({\n id,\n path,\n sats,\n script,\n vin,\n vout,\n height,\n status,\n isDelegate,\n isReward,\n });\n\n if (this.isAlreadyStored({ id, vout })) {\n this.updateUTXO({ id, vout });\n } else {\n // If this new UTXO is a reward with one vin (i.e: a Stake), we'll backtrace the input\n if (isReward && vin?.length === 1) {\n const cStakeInput = this.getUTXO(vin[0].txid, vin[0].vout);\n\n // And if the input is in our wallet, remove it\n if (cStakeInput) {\n this.removeUTXO(cStakeInput);\n }\n }\n this.UTXOs.push(newUTXO);\n }\n\n // Re-render the Balance UIs\n getBalance(true);\n getStakingBalance(true);\n }\n\n /**\n * Update an existing UTXO, by confirming its pending status\n * The UTXO must be in\n * @param {Object} UTXO - Object to be deconstructed\n * @param {String} UTXO.id - Transaction id\n * @param {Number} UTXO.vout - vout\n */\n updateUTXO({ id, vout }) {\n if (debug) {\n console.assert(\n this.isAlreadyStored({ id, vout }),\n 'Debug Mode: updateUTXO must be called with an existing UTXO'\n );\n }\n const cUTXO = this.UTXOs.find(\n (utxo) => utxo.id === id && utxo.vout == vout\n );\n switch (cUTXO.status) {\n case Mempool.PENDING:\n cUTXO.status = Mempool.CONFIRMED;\n break;\n }\n getBalance(true);\n getStakingBalance(true);\n }\n\n /**\n * Remove a UTXO completely from our wallet\n * @param {UTXO} cUTXO - UTXO to remove\n */\n removeUTXO(cUTXO) {\n this.UTXOs = this.UTXOs.filter((utxo) => !utxo.equalsUTXO(cUTXO));\n }\n\n /**\n * Remove a UTXO completely from our wallet, with a 12 minute delay given his id, path and vout\n * @param {Object} UTXO\n * @param {String} UTXO.id - Transaction ID\n * @param {Number} UTXO.vout - Output position of this transaction\n */\n autoRemoveUTXO({ id, vout }) {\n for (const cUTXO of this.UTXOs) {\n // Loop given + internal UTXOs to find a match, then start the delayed removal\n if (cUTXO.id === id && cUTXO.vout === vout) {\n cUTXO.status = Mempool.REMOVED;\n this.removeWithDelay(12, cUTXO);\n return;\n }\n }\n console.error(\n 'Mempool: Failed to find UTXO ' +\n id +\n ' (' +\n vout +\n ') for auto-removal!'\n );\n }\n\n /**\n * Remove many UTXOs completely from our wallet, with a 12 minute delay\n * @param {Array} arrUTXOs - UTXOs to remove\n */\n autoRemoveUTXOs(arrUTXOs) {\n for (const cNewUTXO of arrUTXOs) {\n for (const cUTXO of this.UTXOs) {\n // Loop given + internal UTXOs to find a match, then start the delayed removal\n if (cUTXO.equalsUTXO(cNewUTXO)) {\n cUTXO.status = Mempool.REMOVED;\n this.removeWithDelay(12, cUTXO);\n break;\n }\n }\n }\n }\n\n /**\n * Fetches an array of confirmed UTXOs, an easier alias to {@link getUTXOsByState}\n * @returns {Array} `array` - An array of UTXOs\n */\n getConfirmed() {\n return this.getUTXOsByState(Mempool.CONFIRMED);\n }\n\n /**\n * Get standard, non delegated, UTXOs\n * @returns {Array} Non delegated utxos\n */\n getStandardUTXOs() {\n return this.UTXOs.filter(\n (cUTXO) => cUTXO.status !== Mempool.REMOVED && !cUTXO.isDelegate\n );\n }\n\n /**\n * Get delegated UTXOs\n * @returns {Array} Delegated UTXOs\n */\n getDelegatedUTXOs() {\n return this.UTXOs.filter(\n (cUTXO) => cUTXO.status !== Mempool.REMOVED && cUTXO.isDelegate\n );\n }\n\n /**\n * Returns the real-time balance of the wallet (all addresses)\n * @returns {Number} Balance in satoshis\n */\n getBalance() {\n // Fetch 'standard' balances: the sum of all Confirmed or Unconfirmed transactions (excluding Masternode collaterals)\n return this.getStandardUTXOs()\n .filter((cUTXO) => !isMasternodeUTXO(cUTXO)) // TODO: add masternode\n .reduce((a, b) => a + b.sats, 0);\n }\n\n /**\n * Returns if a UTXO is valid\n * @param {UTXO} cUTXO - UTXO\n * @returns {Boolean} `true` if the reward UTXO is spendable, `false` if not\n */\n static isValidUTXO(cUTXO) {\n if (cUTXO.isReward) {\n return getNetwork().cachedBlockCount - cUTXO.height > 100;\n } else {\n return true;\n }\n }\n\n /**\n * Returns the real-time delegated balance of the wallet (all addresses)\n * @returns {Number} Delegated balance in satoshis\n */\n getDelegatedBalance() {\n return this.getDelegatedUTXOs().reduce((a, b) => a + b.sats, 0);\n }\n\n /**\n * Subscribes to network events\n * @param {Network} network\n */\n subscribeToNetwork() {\n getEventEmitter().on('utxo', async (utxos) => {\n for (const utxo of utxos) {\n // If we have the UTXO, we update it's confirmation status\n if (this.isAlreadyStored({ id: utxo.txid, vout: utxo.vout })) {\n this.updateUTXO({ id: utxo.txid, vout: utxo.vout });\n continue;\n }\n // If the UTXO is new, we'll process it and add it internally\n this.addUTXO(await getNetwork().getUTXOFullInfo(utxo));\n }\n });\n }\n}\n","import { Mempool } from './mempool.js';\nimport Masternode from './masternode.js';\nimport { ALERTS, tr, start as i18nStart, translation } from './i18n.js';\nimport * as jdenticon from 'jdenticon';\nimport {\n masterKey,\n hasEncryptedWallet,\n importWallet,\n encryptWallet,\n decryptWallet,\n getNewAddress,\n getDerivationPath,\n LegacyMasterKey,\n} from './wallet.js';\nimport { getNetwork, HistoricalTxType } from './network.js';\nimport {\n start as settingsStart,\n cExplorer,\n debug,\n cMarket,\n strCurrency,\n setColdStakingAddress,\n strColdStakingAddress,\n nDisplayDecimals,\n} from './settings.js';\nimport { createAndSendTransaction, signTransaction } from './transactions.js';\nimport {\n createAlert,\n confirmPopup,\n sanitizeHTML,\n MAP_B58,\n parseBIP21Request,\n isValidBech32,\n isBase64,\n sleep,\n beautifyNumber,\n isStandardAddress,\n} from './misc.js';\nimport { cChainParams, COIN, MIN_PASS_LENGTH } from './chain_params.js';\nimport { decrypt } from './aes-gcm.js';\n\nimport { registerWorker } from './native.js';\nimport { refreshPriceDisplay } from './prices.js';\nimport { Address6 } from 'ip-address';\nimport { getEventEmitter } from './event_bus.js';\nimport { scanQRCode } from './scanner.js';\nimport { Database } from './database.js';\nimport bitjs from './bitTrx.js';\nimport { checkForUpgrades } from './changelog.js';\nimport { FlipDown } from './flipdown.js';\nimport {\n cReceiveType,\n getNameOrAddress,\n guiAddContactPrompt,\n guiCheckRecipientInput,\n guiToggleReceiveType,\n} from './contacts-book.js';\nimport { Buffer } from 'buffer';\nimport { Account } from './accounts.js';\n\n/** A flag showing if base MPW is fully loaded or not */\nexport let fIsLoaded = false;\n\n/** A getter for the flag showing if base MPW is fully loaded or not */\nexport function isLoaded() {\n return fIsLoaded;\n}\n\nexport let doms = {};\n\nexport async function start() {\n doms = {\n domNavbarToggler: document.getElementById('navbarToggler'),\n domDashboard: document.getElementById('dashboard'),\n domGuiStaking: document.getElementById('guiStaking'),\n domGuiWallet: document.getElementById('guiWallet'),\n domGettingStartedBtn: document.getElementById('gettingStartedBtn'),\n domGuiBalance: document.getElementById('guiBalance'),\n domGuiBalanceTicker: document.getElementById('guiBalanceTicker'),\n domGuiBalanceValue: document.getElementById('guiBalanceValue'),\n domGuiBalanceValueCurrency: document.getElementById(\n 'guiBalanceValueCurrency'\n ),\n domGuiStakingValue: document.getElementById('guiStakingValue'),\n domGuiStakingValueCurrency: document.getElementById(\n 'guiStakingValueCurrency'\n ),\n domGuiBalanceBox: document.getElementById('guiBalanceBox'),\n domBalanceReload: document.getElementById('balanceReload'),\n domBalanceReloadStaking: document.getElementById(\n 'balanceReloadStaking'\n ),\n domGuiBalanceStaking: document.getElementById('guiBalanceStaking'),\n domGuiBalanceStakingTicker: document.getElementById(\n 'guiBalanceStakingTicker'\n ),\n domGuiStakingLoadMore: document.getElementById('stakingLoadMore'),\n domGuiStakingLoadMoreIcon: document.getElementById(\n 'stakingLoadMoreIcon'\n ),\n domGuiBalanceBoxStaking: document.getElementById(\n 'guiBalanceBoxStaking'\n ),\n domStakeAmount: document.getElementById('delegateAmount'),\n domUnstakeAmount: document.getElementById('undelegateAmount'),\n domStakeTab: document.getElementById('stakeTab'),\n domAddress1s: document.getElementById('address1s'),\n domSendAmountCoins: document.getElementById('sendAmountCoins'),\n domSendAmountCoinsTicker: document.getElementById(\n 'sendAmountCoinsTicker'\n ),\n domSendAmountValue: document.getElementById('sendAmountValue'),\n domSendAmountValueCurrency: document.getElementById(\n 'sendAmountValueCurrency'\n ),\n domStakeAmountCoinsTicker: document.getElementById(\n 'stakeAmountCoinsTicker'\n ),\n domStakeAmountValueCurrency: document.getElementById(\n 'stakeAmountValueCurrency'\n ),\n domStakeAmountValue: document.getElementById('stakeAmountValue'),\n domUnstakeAmountCoinsTicker: document.getElementById(\n 'unstakeAmountCoinsTicker'\n ),\n domUnstakeAmountValueCurrency: document.getElementById(\n 'unstakeAmountValueCurrency'\n ),\n\n domUnstakeAmountValue: document.getElementById('unstakeAmountValue'),\n domGuiViewKey: document.getElementById('guiViewKey'),\n domModalQR: document.getElementById('ModalQR'),\n domModalQrLabel: document.getElementById('ModalQRLabel'),\n domModalQrReceiveTypeBtn: document.getElementById(\n 'ModalQRReceiveTypeBtn'\n ),\n domModalQRReader: document.getElementById('qrReaderModal'),\n domQrReaderStream: document.getElementById('qrReaderStream'),\n domCloseQrReaderBtn: document.getElementById('closeQrReader'),\n domModalWalletBreakdown: document.getElementById(\n 'walletBreakdownModal'\n ),\n domWalletBreakdownCanvas: document.getElementById(\n 'walletBreakdownCanvas'\n ),\n domPrefix: document.getElementById('prefix'),\n domPrefixNetwork: document.getElementById('prefixNetwork'),\n domWalletToggle: document.getElementById('wToggle'),\n domGenerateWallet: document.getElementById('generateWallet'),\n domGenVanityWallet: document.getElementById('generateVanityWallet'),\n domGenHardwareWallet: document.getElementById('generateHardwareWallet'),\n //GOVERNANCE ELEMENTS\n domGovTab: document.getElementById('governanceTab'),\n domGovProposalsTable: document.getElementById('proposalsTable'),\n domGovProposalsTableBody: document.getElementById('proposalsTableBody'),\n domTotalGovernanceBudget: document.getElementById(\n 'totalGovernanceBudget'\n ),\n domTotalGovernanceBudgetValue: document.getElementById(\n 'totalGovernanceBudgetValue'\n ),\n domAllocatedGovernanceBudget: document.getElementById(\n 'allocatedGovernanceBudget'\n ),\n domAllocatedGovernanceBudgetValue: document.getElementById(\n 'allocatedGovernanceBudgetValue'\n ),\n domAllocatedGovernanceBudget2: document.getElementById(\n 'allocatedGovernanceBudget2'\n ),\n domAllocatedGovernanceBudgetValue2: document.getElementById(\n 'allocatedGovernanceBudgetValue2'\n ),\n domGovProposalsContestedTable: document.getElementById(\n 'proposalsContestedTable'\n ),\n domGovProposalsContestedTableBody: document.getElementById(\n 'proposalsContestedTableBody'\n ),\n //MASTERNODE ELEMENTS\n domCreateMasternode: document.getElementById('createMasternode'),\n domControlMasternode: document.getElementById('controlMasternode'),\n domAccessMasternode: document.getElementById('accessMasternode'),\n domMnAccessMasternodeText: document.getElementById(\n 'accessMasternodeText'\n ),\n domMnCreateType: document.getElementById('mnCreateType'),\n domMnTextErrors: document.getElementById('mnTextErrors'),\n domMnIP: document.getElementById('mnIP'),\n domMnTxId: document.getElementById('mnTxId'),\n domMnPrivateKey: document.getElementById('mnPrivateKey'),\n domMnDashboard: document.getElementById('mnDashboard'),\n domMnProtocol: document.getElementById('mnProtocol'),\n domMnStatus: document.getElementById('mnStatus'),\n domMnNetType: document.getElementById('mnNetType'),\n domMnNetIP: document.getElementById('mnNetIP'),\n domMnLastSeen: document.getElementById('mnLastSeen'),\n\n domAccessWallet: document.getElementById('accessWallet'),\n domImportWallet: document.getElementById('importWallet'),\n domImportWalletText: document.getElementById('importWalletText'),\n domAccessWalletBtn: document.getElementById('accessWalletBtn'),\n domVanityUiButtonTxt: document.getElementById('vanButtonText'),\n domGenKeyWarning: document.getElementById('genKeyWarning'),\n domEncryptWalletLabel: document.getElementById('encryptWalletLabel'),\n domEncryptPasswordCurrent: document.getElementById(\n 'changePassword-current'\n ),\n domEncryptPasswordBox: document.getElementById('encryptPassword'),\n domEncryptPasswordFirst: document.getElementById('newPassword'),\n domEncryptPasswordSecond: document.getElementById('newPasswordRetype'),\n domGuiAddress: document.getElementById('guiAddress'),\n domGenIt: document.getElementById('genIt'),\n domReqDesc: document.getElementById('reqDesc'),\n domReqDisplay: document.getElementById('reqDescDisplay'),\n domIdenticon: document.getElementById('identicon'),\n domPrivKey: document.getElementById('privateKey'),\n domPrivKeyPassword: document.getElementById('privateKeyPassword'),\n domAvailToDelegate: document.getElementById('availToDelegate'),\n domAvailToUndelegate: document.getElementById('availToUndelegate'),\n domAnalyticsDescriptor: document.getElementById('analyticsDescriptor'),\n domStakingRewardsList: document.getElementById(\n 'staking-rewards-content'\n ),\n domStakingRewardsTitle: document.getElementById(\n 'staking-rewards-title'\n ),\n domMnemonicModalContent: document.getElementById(\n 'ModalMnemonicContent'\n ),\n domMnemonicModalButton: document.getElementById(\n 'modalMnemonicConfirmButton'\n ),\n domMnemonicModalPassphrase: document.getElementById(\n 'ModalMnemonicPassphrase'\n ),\n domExportPrivateKey: document.getElementById('exportPrivateKeyText'),\n domExportWallet: document.getElementById('guiExportWalletItem'),\n domWipeWallet: document.getElementById('guiWipeWallet'),\n domRestoreWallet: document.getElementById('guiRestoreWallet'),\n domNewAddress: document.getElementById('guiNewAddress'),\n domRedeemTitle: document.getElementById('redeemCodeModalTitle'),\n domRedeemCodeUse: document.getElementById('redeemCodeUse'),\n domRedeemCodeCreate: document.getElementById('redeemCodeCreate'),\n domRedeemCodeGiftIconBox: document.getElementById(\n 'redeemCodeGiftIconBox'\n ),\n domRedeemCodeGiftIcon: document.getElementById('redeemCodeGiftIcon'),\n domRedeemCodeETA: document.getElementById('redeemCodeETA'),\n domRedeemCodeProgress: document.getElementById('redeemCodeProgress'),\n domRedeemCodeInputBox: document.getElementById('redeemCodeInputBox'),\n domRedeemCodeInput: document.getElementById('redeemCodeInput'),\n domRedeemCodeConfirmBtn: document.getElementById(\n 'redeemCodeModalConfirmButton'\n ),\n domRedeemCodeModeRedeemBtn: document.getElementById(\n 'redeemCodeModeRedeem'\n ),\n domRedeemCodeModeCreateBtn: document.getElementById(\n 'redeemCodeModeCreate'\n ),\n domRedeemCodeCreateInput: document.getElementById(\n 'redeemCodeCreateInput'\n ),\n domRedeemCodeCreateAmountInput: document.getElementById(\n 'redeemCodeCreateAmountInput'\n ),\n domRedeemCodeCreatePendingList: document.getElementById(\n 'redeemCodeCreatePendingList'\n ),\n domPromoTable: document.getElementById('promo-table'),\n domContactsTable: document.getElementById('contactsList'),\n domActivityList: document.getElementById('activity-list-content'),\n domActivityLoadMore: document.getElementById('activityLoadMore'),\n domActivityLoadMoreIcon: document.getElementById(\n 'activityLoadMoreIcon'\n ),\n domConfirmModalDialog: document.getElementById('confirmModalDialog'),\n domConfirmModalMain: document.getElementById('confirmModalMain'),\n domConfirmModalHeader: document.getElementById('confirmModalHeader'),\n domConfirmModalTitle: document.getElementById('confirmModalTitle'),\n domConfirmModalContent: document.getElementById('confirmModalContent'),\n domConfirmModalButtons: document.getElementById('confirmModalButtons'),\n domConfirmModalConfirmButton: document.getElementById(\n 'confirmModalConfirmButton'\n ),\n domConfirmModalCancelButton: document.getElementById(\n 'confirmModalCancelButton'\n ),\n\n masternodeLegacyAccessText:\n 'Access the masternode linked to this address
Note: the masternode MUST have been already created (however it can be online or offline)
If you want to create a new masternode access with a HD wallet',\n masternodeHDAccessText:\n \"Access your masternodes if you have any! If you don't you can create one\",\n // Aggregate menu screens and links for faster switching\n arrDomScreens: document.getElementsByClassName('tabcontent'),\n arrDomScreenLinks: document.getElementsByClassName('tablinks'),\n // Alert DOM element\n domAlertPos: document.getElementsByClassName('alertPositioning')[0],\n domNetwork: document.getElementById('Network'),\n domChangePasswordContainer: document.getElementById(\n 'changePassword-container'\n ),\n domDebug: document.getElementById('Debug'),\n domTestnet: document.getElementById('Testnet'),\n domCurrencySelect: document.getElementById('currency'),\n domExplorerSelect: document.getElementById('explorer'),\n domNodeSelect: document.getElementById('node'),\n domAutoSwitchToggle: document.getElementById('autoSwitchToggler'),\n domTranslationSelect: document.getElementById('translation'),\n domDisplayDecimalsSlider: document.getElementById('displayDecimals'),\n domDisplayDecimalsSliderDisplay:\n document.getElementById('sliderDisplay'),\n domBlackBack: document.getElementById('blackBack'),\n domWalletSettings: document.getElementById('settingsWallet'),\n domDisplaySettings: document.getElementById('settingsDisplay'),\n domWalletSettingsBtn: document.getElementById('settingsWalletBtn'),\n domDisplaySettingsBtn: document.getElementById('settingsDisplayBtn'),\n domVersion: document.getElementById('version'),\n domFlipdown: document.getElementById('flipdown'),\n domTestnetToggler: document.getElementById('testnetToggler'),\n };\n await i18nStart();\n await loadImages();\n\n // Enable all Bootstrap Tooltips\n $(function () {\n $('#displayDecimals').tooltip({\n template:\n '
',\n });\n $('[data-toggle=\"tooltip\"]').tooltip();\n });\n\n // Set decimal slider event\n const sliderElement = document.getElementById('displayDecimals');\n function handleDecimalSlider() {\n setTimeout(() => {\n try {\n if (window.innerWidth > 991) {\n const sliderHalf = Math.round(\n document\n .getElementById('displayDecimals')\n .getBoundingClientRect().width / 2\n );\n const sliderBegin = -sliderHalf + 28;\n const stepVal = (sliderHalf * 2) / 8 - 6.45;\n const sliderValue = parseInt(sliderElement.value) + 1;\n\n document.querySelector('.sliderStyle').style.left = `${\n sliderBegin - stepVal + stepVal * sliderValue\n }px`;\n document.querySelector('.tooltip-inner').innerHTML =\n sliderValue - 1;\n }\n } catch (e) {}\n }, 10);\n }\n sliderElement.addEventListener('input', handleDecimalSlider);\n sliderElement.addEventListener('mouseover', handleDecimalSlider);\n\n // Register Input Pair events\n doms.domSendAmountCoins.oninput = () => {\n updateAmountInputPair(\n doms.domSendAmountCoins,\n doms.domSendAmountValue,\n true\n );\n };\n doms.domSendAmountValue.oninput = () => {\n updateAmountInputPair(\n doms.domSendAmountCoins,\n doms.domSendAmountValue,\n false\n );\n };\n\n /** Staking (Stake) */\n doms.domStakeAmount.oninput = () => {\n updateAmountInputPair(\n doms.domStakeAmount,\n doms.domStakeAmountValue,\n true\n );\n };\n doms.domStakeAmountValue.oninput = () => {\n updateAmountInputPair(\n doms.domStakeAmount,\n doms.domStakeAmountValue,\n false\n );\n };\n\n /** Staking (Unstake) */\n doms.domUnstakeAmount.oninput = () => {\n updateAmountInputPair(\n doms.domUnstakeAmount,\n doms.domUnstakeAmountValue,\n true\n );\n };\n doms.domUnstakeAmountValue.oninput = () => {\n updateAmountInputPair(\n doms.domUnstakeAmount,\n doms.domUnstakeAmountValue,\n false\n );\n };\n\n // Register native app service\n registerWorker();\n\n // Configure Identicon\n jdenticon.configure();\n\n // URL-Query request processing\n const urlParams = new URLSearchParams(window.location.search);\n\n // Check for a payment request address\n const reqTo = urlParams.has('pay') ? urlParams.get('pay') : '';\n\n // Check for a payment request amount\n const reqAmount = urlParams.has('amount')\n ? parseFloat(urlParams.get('amount'))\n : 0;\n await settingsStart();\n\n // Customise the UI if a saved wallet exists\n if (await hasEncryptedWallet()) {\n // Hide the 'Generate wallet' buttons\n doms.domGenerateWallet.style.display = 'none';\n doms.domGenVanityWallet.style.display = 'none';\n const database = await Database.getInstance();\n const { publicKey } = await database.getAccount();\n\n // Import the wallet, and toggle the startup flag, which delegates the chain data refresh to settingsStart();\n if (publicKey) {\n await importWallet({ newWif: publicKey, fStartup: true });\n\n // Update the \"Receive\" UI to apply Translation and Contacts updates\n await guiToggleReceiveType(cReceiveType);\n\n // Check for Add Contact calls\n if (urlParams.has('addcontact')) {\n // Quick sanity check\n const strURI = urlParams.get('addcontact');\n if (strURI.includes(':')) {\n // Split to 'name' and 'pubkey'\n const arrParts = strURI.split(':');\n\n // Convert Name from HEX to UTF-8\n const strName = Buffer.from(arrParts[0], 'hex').toString(\n 'utf8'\n );\n const strPubkey = arrParts[1];\n\n // Prompt the user to add the Contact\n guiAddContactPrompt(sanitizeHTML(strName), strPubkey);\n }\n } else if (reqTo.length || reqAmount > 0) {\n // Payment processor popup\n guiPreparePayment(\n reqTo,\n reqAmount,\n urlParams.has('desc') ? urlParams.get('desc') : ''\n );\n }\n } else {\n // Display the password unlock upfront\n await accessOrImportWallet();\n }\n } else {\n // Just load the block count, for use in non-wallet areas\n getNetwork().getBlockCount();\n }\n\n subscribeToNetworkEvents();\n\n doms.domPrefix.value = '';\n doms.domPrefixNetwork.innerText =\n cChainParams.current.PUBKEY_PREFIX.join(' or ');\n // If allowed by settings: submit a simple 'hit' (app load) to Labs Analytics\n getNetwork().submitAnalytics('hit');\n setInterval(() => {\n // Refresh blockchain data\n refreshChainData();\n\n // Fetch the PIVX prices\n refreshPriceDisplay();\n }, 15000);\n\n // After reaching here; we know MPW's base is fully loaded!\n fIsLoaded = true;\n\n // Check for recent upgrades, display the changelog\n checkForUpgrades();\n\n // If we haven't already (due to having no wallet, etc), display the Dashboard\n doms.domDashboard.click();\n\n // Update the Encryption UI (If the user has a wallet, then it changes to \"Change Password\" rather than \"Encrypt Wallet\")\n await updateEncryptionGUI();\n}\n\nfunction subscribeToNetworkEvents() {\n getEventEmitter().on('network-toggle', (value) => {\n doms.domNetwork.innerHTML =\n '';\n });\n\n getEventEmitter().on('sync-status', (value) => {\n switch (value) {\n case 'start':\n // Play reload anim\n doms.domBalanceReload.classList.add('playAnim');\n doms.domBalanceReloadStaking.classList.add('playAnim');\n break;\n case 'stop':\n doms.domBalanceReload.classList.remove('playAnim');\n doms.domBalanceReloadStaking.classList.remove('playAnim');\n break;\n }\n });\n\n getEventEmitter().on('transaction-sent', (success, result) => {\n if (success) {\n doms.domAddress1s.value = '';\n doms.domSendAmountCoins.innerHTML = '';\n createAlert(\n 'success',\n `${ALERTS.TX_SENT}
${sanitizeHTML(result)}`,\n result ? 1250 + result.length * 50 : 3000\n );\n // If allowed by settings: submit a simple 'tx' ping to Labs Analytics\n getNetwork().submitAnalytics('transaction');\n } else {\n console.error('Error sending transaction:');\n console.error(result);\n createAlert('warning', ALERTS.TX_FAILED, 2500);\n }\n });\n}\n\n// WALLET STATE DATA\nexport const mempool = new Mempool();\nlet exportHidden = false;\nlet isTestnetLastState = cChainParams.current.isTestnet;\n\n/**\n * @type {FlipDown | null}\n */\nlet governanceFlipdown = null;\n\n/**\n * Open a UI 'tab' menu, and close all other tabs, intended for frontend use\n * @param {Event} evt - The click event target\n * @param {string} tabName - The name of the tab to load\n */\nexport function openTab(evt, tabName) {\n // Only allow switching tabs if MPw is loaded\n if (!isLoaded()) return;\n\n // Hide all screens and deactivate link highlights\n for (const domScreen of doms.arrDomScreens)\n domScreen.style.display = 'none';\n for (const domLink of doms.arrDomScreenLinks)\n domLink.classList.remove('active');\n\n // Show and activate the given screen\n document.getElementById(tabName).style.display = 'block';\n evt.currentTarget.classList.add('active');\n\n // Close the navbar if it's not already closed\n if (!doms.domNavbarToggler.className.includes('collapsed'))\n doms.domNavbarToggler.click();\n\n if (tabName === 'Governance') {\n updateGovernanceTab();\n } else if (tabName === 'Masternode') {\n updateMasternodeTab();\n } else if (\n tabName === 'StakingTab' &&\n getNetwork().arrTxHistory.length === 0\n ) {\n // Refresh the TX list\n updateActivityGUI(true, false);\n } else if (\n tabName === 'keypair' &&\n getNetwork().arrTxHistory.length === 0\n ) {\n // Refresh the TX list\n updateActivityGUI(false, false);\n }\n}\n\n/**\n * Updates the GUI ticker among all elements; useful for Network Switching\n */\nexport function updateTicker() {\n // Update the Dashboard currency\n doms.domGuiBalanceValueCurrency.innerText = strCurrency.toUpperCase();\n\n // Update the Stake Dashboard currency\n doms.domGuiStakingValueCurrency.innerText = strCurrency.toUpperCase();\n\n // Update the Send menu ticker and currency\n doms.domSendAmountValueCurrency.innerText = strCurrency.toUpperCase();\n doms.domSendAmountCoinsTicker.innerText = cChainParams.current.TICKER;\n\n // Update the Stake/Unstake menu ticker and currency\n // Stake\n doms.domStakeAmountValueCurrency.innerText = strCurrency.toUpperCase();\n doms.domStakeAmountCoinsTicker.innerText = cChainParams.current.TICKER;\n\n // Unstake\n doms.domUnstakeAmountValueCurrency.innerText = strCurrency.toUpperCase();\n doms.domUnstakeAmountCoinsTicker.innerText = cChainParams.current.TICKER;\n}\n\n/**\n * Return locale settings best for displaying the user-selected currency\n * @param {Number} nAmount - The amount in Currency\n */\nexport function optimiseCurrencyLocale(nAmount) {\n // Allow manipulating the value, if necessary\n let nValue = nAmount;\n\n // Find the best fitting native-locale\n const cLocale = Intl.supportedValuesOf('currency').includes(\n strCurrency.toUpperCase()\n )\n ? {\n style: 'currency',\n currency: strCurrency,\n currencyDisplay: 'narrowSymbol',\n }\n : { maximumFractionDigits: 8, minimumFractionDigits: 8 };\n\n // Catch display edge-cases; like Satoshis having decimals.\n switch (strCurrency) {\n case 'sats':\n nValue = Math.round(nValue);\n cLocale.maximumFractionDigits = 0;\n cLocale.minimumFractionDigits = 0;\n }\n\n // Return display-optimised Value and Locale pair.\n return { nValue, cLocale };\n}\n\n/**\n * Update a 'price value' DOM display for the given balance type\n * @param {HTMLElement} domValue\n * @param {boolean} fCold\n */\nexport async function updatePriceDisplay(domValue, fCold = false) {\n // Update currency values\n const nPrice = await cMarket.getPrice(strCurrency);\n\n if (nPrice) {\n // Calculate the value\n const nCurrencyValue =\n ((fCold ? getStakingBalance() : getBalance()) / COIN) * nPrice;\n\n const { nValue, cLocale } = optimiseCurrencyLocale(nCurrencyValue);\n\n // Update the DOM\n domValue.innerText = nValue.toLocaleString('en-gb', cLocale);\n }\n}\n\nexport function getBalance(updateGUI = false) {\n const nBalance = mempool.getBalance();\n const nCoins = nBalance / COIN;\n\n // Update the GUI too, if chosen\n if (updateGUI) {\n // Set the balance, and adjust font-size for large balance strings\n const strBal = nCoins.toFixed(nDisplayDecimals);\n const nLen = strBal.length;\n doms.domGuiBalance.innerHTML = beautifyNumber(\n strBal,\n nLen >= 10 ? '17px' : '25px'\n );\n doms.domAvailToDelegate.innerHTML =\n beautifyNumber(strBal) + ' ' + cChainParams.current.TICKER;\n\n // Update tickers\n updateTicker();\n\n // Update price displays\n updatePriceDisplay(doms.domGuiBalanceValue);\n }\n\n return nBalance;\n}\n\nexport function getStakingBalance(updateGUI = false) {\n const nBalance = mempool.getDelegatedBalance();\n const nCoins = nBalance / COIN;\n\n if (updateGUI) {\n // Set the balance, and adjust font-size for large balance strings\n const strBal = nCoins.toFixed(nDisplayDecimals);\n const nLen = strBal.length;\n doms.domGuiBalanceStaking.innerHTML = beautifyNumber(\n strBal,\n nLen >= 10 ? '17px' : '25px'\n );\n doms.domAvailToUndelegate.innerHTML =\n beautifyNumber(strBal) + ' ' + cChainParams.current.TICKER;\n\n // Update tickers\n updateTicker();\n\n // Update price displays\n updatePriceDisplay(doms.domGuiStakingValue, true);\n }\n\n return nBalance;\n}\n\n/**\n * Fill a 'Coin Amount' with all of a balance type, and update the 'Coin Value'\n * @param {HTMLInputElement} domCoin - The 'Coin Amount' input element\n * @param {HTMLInputElement} domValue - Th 'Coin Value' input element\n * @param {boolean} fCold - Use the Cold Staking balance, or Available balance\n */\nexport function selectMaxBalance(domCoin, domValue, fCold = false) {\n domCoin.value = (fCold ? getStakingBalance() : getBalance()) / COIN;\n // Update the Send menu's value (assumption: if it's not a Cold balance, it's probably for Sending!)\n updateAmountInputPair(domCoin, domValue, true);\n}\n\n/**\n * Prompt a QR scan for a Payment (Address or BIP21)\n */\nexport async function openSendQRScanner() {\n const cScan = await scanQRCode();\n\n if (!cScan || !cScan.data) return;\n\n /* Check what data the scan contains - for the various QR request types */\n\n // Plain address (Length and prefix matches)\n if (isStandardAddress(cScan.data)) {\n return guiPreparePayment(cScan.data);\n }\n\n // Shield address (Valid bech32 string)\n if (isValidBech32(cScan.data).valid) {\n return guiPreparePayment(cScan.data);\n }\n\n // BIP21 Payment Request (Optional 'amount' and 'label')\n const cBIP21Req = parseBIP21Request(cScan.data);\n if (cBIP21Req) {\n return guiPreparePayment(\n cBIP21Req.address,\n cBIP21Req.options.amount || 0,\n cBIP21Req.options.label || ''\n );\n }\n\n // MPW Contact Request URI\n if (cScan.data.includes('addcontact=')) {\n // Parse as URL Params\n const cURL = new URL(cScan.data);\n const urlParams = new URLSearchParams(cURL.search);\n const strURI = urlParams.get('addcontact');\n\n // Sanity check the URI\n if (strURI?.includes(':')) {\n // Split to 'name' and 'pubkey'\n const arrParts = strURI.split(':');\n\n // If the wallet is encrypted, prompt the user to (optionally) add the Contact, before the Tx\n const fUseName = (await hasEncryptedWallet())\n ? await guiAddContactPrompt(\n sanitizeHTML(arrParts[0]),\n arrParts[1],\n false\n )\n : false;\n\n // Prompt for payment\n return guiPreparePayment(fUseName ? arrParts[0] : arrParts[1]);\n }\n }\n\n // No idea what this is...\n createAlert(\n 'warning',\n `\"${sanitizeHTML(\n cScan.data.substring(0, Math.min(cScan.data.length, 6))\n )}…\" ${ALERTS.QR_SCANNER_BAD_RECEIVER}`,\n 7500\n );\n}\n\n/**\n * Generate a DOM-optimised activity list\n * @param {Array} arrTXs - The TX array to compute the list from\n * @param {boolean} fRewards - If this list is for Reward transactions\n * @returns {Promise} HTML - The Activity List in HTML string form\n */\nexport async function createActivityListHTML(arrTXs, fRewards = false) {\n const cNet = getNetwork();\n const cDB = await Database.getInstance();\n const cAccount = await cDB.getAccount();\n\n // Prepare the table HTML\n let strList = `\n \n \n \n \n \n \n \n \n \n `;\n\n // Prepare time formatting\n const dateOptions = {\n year: '2-digit',\n month: '2-digit',\n day: '2-digit',\n };\n const timeOptions = {\n hour: '2-digit',\n minute: '2-digit',\n hour12: true,\n };\n\n // And also keep track of our last Tx's timestamp, to re-use a cache, which is much faster than the slow `.toLocaleDateString`\n let prevDateString = '';\n let prevTimestamp = 0;\n\n // Generate the TX list\n for (const cTx of arrTXs) {\n // If no account is loaded, we render nothing!\n if (!masterKey) break;\n\n const dateTime = new Date(cTx.time * 1000);\n\n // If this Tx is older than 24h, then hit the `Date` cache logic, otherwise, use a `Time` and skip it\n let strDate =\n Date.now() / 1000 - cTx.time > 86400\n ? ''\n : dateTime.toLocaleTimeString(undefined, timeOptions);\n if (!strDate) {\n if (\n prevDateString &&\n prevTimestamp - cTx.time * 1000 < 12 * 60 * 60 * 1000\n ) {\n // Use our date cache\n strDate = prevDateString;\n } else {\n // Create a new date, this Tx is too old to use the cache\n prevDateString = dateTime.toLocaleDateString(\n undefined,\n dateOptions\n );\n strDate = prevDateString;\n }\n }\n\n // Update the time cache\n prevTimestamp = cTx.time * 1000;\n\n // Coinbase Transactions (rewards) require 100 confs\n const fConfirmed =\n cNet.cachedBlockCount - cTx.blockHeight >= fRewards ? 100 : 6;\n\n // Choose the correct icon and colour for the Tx type, or a question mark if the type is unknown\n // Defaults: Reward Activity\n let icon = 'fa-gift';\n let colour = 'white';\n\n // Choose the content type, for the Dashboard; use a generative description, otherwise, a TX-ID\n let txContent = fRewards ? cTx.id : translation.activityBlockReward;\n\n // Format the amount to reduce text size\n let formattedAmt = '';\n if (cTx.amount < 0.01) {\n formattedAmt = '<0.01';\n } else if (cTx.amount >= 100) {\n formattedAmt = Math.round(cTx.amount).toString();\n } else {\n formattedAmt = cTx.amount.toFixed(2);\n }\n\n // For 'Send' or 'Receive' TXs: Check if this is a send-to-self transaction\n let fSendToSelf = true;\n if (\n cTx.type === HistoricalTxType.SENT ||\n cTx.type === HistoricalTxType.RECEIVED\n ) {\n // Check all addresses to find our own, caching them for performance\n for (const strAddr of cTx.receivers.concat(cTx.senders)) {\n // If a previous Tx checked this address, skip it, otherwise, check it against our own address(es)\n if (!(await masterKey.isOwnAddress(strAddr))) {\n // External address, this is not a self-only Tx\n fSendToSelf = false;\n }\n }\n }\n\n // Generate an icon, colour and description for the Tx\n if (!fRewards) {\n switch (cTx.type) {\n case HistoricalTxType.STAKE:\n icon = 'fa-gift';\n break;\n case HistoricalTxType.SENT:\n icon = 'fa-minus';\n colour = '#f93c3c';\n // Figure out WHO this was sent to, and focus on them contextually\n if (fSendToSelf) {\n txContent = translation.activitySentToSelf;\n } else {\n // Otherwise, anything to us is likely change, so filter it away\n const arrExternalAddresses = (\n await Promise.all(\n cTx.receivers.map(async (addr) => [\n await masterKey.isOwnAddress(addr),\n addr,\n ])\n )\n )\n .filter(([isOwnAddress, _]) => {\n return !isOwnAddress;\n })\n .map(([_, addr]) =>\n getNameOrAddress(cAccount, addr)\n );\n txContent =\n translation.activitySentTo +\n ' ' +\n (cTx.shieldedOutputs\n ? translation.activityShieldedAddress\n : [\n ...new Set(\n arrExternalAddresses.map((addr) =>\n addr.length >= 32\n ? addr.substring(0, 6)\n : addr\n )\n ),\n ].join(', ') + '...');\n }\n break;\n case HistoricalTxType.RECEIVED: {\n icon = 'fa-plus';\n colour = '#5cff5c';\n // Figure out WHO this was sent from, and focus on them contextually\n // Filter away any of our own addresses\n const arrExternalAddresses = (\n await Promise.all(\n cTx.senders.map(async (addr) => [\n await masterKey.isOwnAddress(addr),\n addr,\n ])\n )\n )\n .filter(([isOwnAddress, _]) => {\n return !isOwnAddress;\n })\n .map(([_, addr]) => getNameOrAddress(cAccount, addr));\n\n if (cTx.shieldedOutputs) {\n txContent = translation.activityReceivedShield;\n } else {\n txContent =\n translation.activityReceivedFrom +\n ' ' +\n [\n ...new Set(\n arrExternalAddresses.map((addr) =>\n addr?.length >= 32\n ? addr.substring(0, 6)\n : addr\n )\n ),\n ].join(', ') +\n '...';\n }\n break;\n }\n case HistoricalTxType.DELEGATION:\n icon = 'fa-snowflake';\n txContent =\n translation.activityDelegatedTo +\n ' ' +\n cTx.receivers[0].substring(0, 6) +\n '...';\n break;\n case HistoricalTxType.UNDELEGATION:\n icon = 'fa-fire';\n txContent = translation.activityUndelegated;\n break;\n default:\n icon = 'fa-question';\n txContent = translation.activityUnknown;\n }\n }\n\n // Render the list element from Tx data\n strList += `\n \n \n \n \n \n `;\n }\n\n // End the table\n strList += `
${translation.time}${\n fRewards ? translation.ID : translation.description\n }${translation.amount}
\n ${strDate}\n \n \n ${sanitizeHTML(\n txContent\n )}\n \n \n ${formattedAmt} ${\n cChainParams.current.TICKER\n }\n \n ${\n fConfirmed\n ? ''\n : ``\n }\n
`;\n\n // Return the HTML string\n return strList;\n}\n\n/**\n * Refreshes the specified activity table, charts and related information\n */\nexport async function updateActivityGUI(fStaking = false, fNewOnly = false) {\n const cNet = getNetwork();\n\n // Prevent the user from spamming refreshes\n if (cNet.historySyncing) return;\n\n // Remember how much history we had previously\n const nPrevHistory = cNet.arrTxHistory.length;\n\n // Choose the Dashboard or Staking UI accordingly\n let domLoadMore = doms.domActivityLoadMore;\n let domLoadMoreIcon = doms.domActivityLoadMoreIcon;\n if (fStaking) {\n domLoadMore = doms.domGuiStakingLoadMore;\n domLoadMoreIcon = doms.domGuiStakingLoadMoreIcon;\n }\n\n // Load rewards from the network, displaying the sync spin icon until finished\n domLoadMoreIcon.classList.add('fa-spin');\n const arrTXs = await cNet.syncTxHistoryChunk(fNewOnly);\n domLoadMoreIcon.classList.remove('fa-spin');\n\n // If there's no change in history size post-sync, then we can cancel here, there's nothing new to render\n if (nPrevHistory === cNet.arrTxHistory.length) return;\n\n // Check if all transactions are loaded\n if (cNet.isHistorySynced) {\n // Hide the load more button\n domLoadMore.style.display = 'none';\n }\n\n // Render the new Activity lists\n renderActivityGUI(arrTXs);\n}\n\n/**\n * Renders the Activity GUIs (without syncing or refreshing)\n * @param {Array} arrTXs\n */\nexport async function renderActivityGUI(arrTXs) {\n // For Staking: Filter the list for only Stakes, display total rewards from known history\n const cNet = getNetwork();\n const arrStakes = arrTXs.filter((a) => a.type === HistoricalTxType.STAKE);\n const nRewards = arrStakes.reduce((a, b) => a + b.amount, 0);\n doms.domStakingRewardsTitle.innerHTML = `${\n cNet.isHistorySynced ? '' : '≥'\n }${sanitizeHTML(nRewards)} ${cChainParams.current.TICKER}`;\n\n // Create and render the Dashboard Activity\n doms.domActivityList.innerHTML = await createActivityListHTML(\n arrTXs,\n false\n );\n // Create and render the Staking History\n doms.domStakingRewardsList.innerHTML = await createActivityListHTML(\n arrStakes,\n true\n );\n}\n\n/**\n * Open the Explorer in a new tab for the current wallet, or a specific address\n * @param {string?} strAddress - Optional address to open, if void, the master key is used\n */\nexport async function openExplorer(strAddress = '') {\n if (masterKey?.isHD && !strAddress) {\n const derivationPath = getDerivationPath(masterKey.isHardwareWallet)\n .split('/')\n .slice(0, 4)\n .join('/');\n const xpub = await masterKey.getxpub(derivationPath);\n window.open(cExplorer.url + '/xpub/' + xpub, '_blank');\n } else {\n const address = strAddress || (await masterKey.getAddress());\n window.open(cExplorer.url + '/address/' + address, '_blank');\n }\n}\n\nasync function loadImages() {\n const images = [\n ['mpw-main-logo', import('../assets/logo.png')],\n ['privateKeyImage', import('../assets/key.png')],\n ];\n\n const promises = images.map(([id, path]) =>\n (async () => {\n document.getElementById(id).src = (await path).default;\n })()\n );\n await Promise.all(promises);\n}\n\nlet audio = null;\nexport async function playMusic() {\n // On first play: load the audio into memory from the host\n if (audio === null) {\n // Dynamically load the file\n audio = new Audio((await import('../assets/music.mp3')).default);\n }\n\n // Play or Pause\n if (audio.paused || audio.ended) {\n audio.play();\n for (const domImg of document.getElementsByTagName('img'))\n domImg.classList.add('discoFilter');\n } else {\n audio.pause();\n for (const domImg of document.getElementsByTagName('img'))\n domImg.classList.remove('discoFilter');\n }\n}\n\nexport function unblurPrivKey() {\n if (\n document\n .getElementById('exportPrivateKeyText')\n .classList.contains('blurred')\n ) {\n document\n .getElementById('exportPrivateKeyText')\n .classList.remove('blurred');\n } else {\n document\n .getElementById('exportPrivateKeyText')\n .classList.add('blurred');\n }\n}\n\nexport function toggleBottomMenu(dom, ani) {\n let element = document.getElementById(dom);\n if (element.classList.contains(ani)) {\n element.classList.remove(ani);\n doms.domBlackBack.classList.remove('d-none');\n setTimeout(() => {\n doms.domBlackBack.classList.remove('blackBackHide');\n }, 10);\n } else {\n element.classList.add(ani);\n doms.domBlackBack.classList.add('blackBackHide');\n setTimeout(() => {\n doms.domBlackBack.classList.add('d-none');\n }, 150);\n }\n}\n\n/**\n * Updates an Amount Input UI pair ('Coin' and 'Value' input boxes) in relation to the input box used\n * @param {HTMLInputElement} domCoin - The DOM input for the Coin amount\n * @param {HTMLInputElement} domValue - The DOM input for the Value amount\n * @param {boolean} fCoinEdited - `true` if Coin, `false` if Value\n */\nexport async function updateAmountInputPair(domCoin, domValue, fCoinEdited) {\n // Fetch the price in the user's preferred currency\n const nPrice = await cMarket.getPrice(strCurrency);\n\n // If there is no price loaded, then we just won't do anything\n if (!nPrice) return;\n\n if (fCoinEdited) {\n // If the 'Coin' input is edited, then update the 'Value' input with it's converted currency\n const nValue = Number(domCoin.value) * nPrice;\n domValue.value = nValue <= 0 ? '' : nValue;\n } else {\n // If the 'Value' input is edited, then update the 'Coin' input with the reversed conversion rate\n const nValue = Number(domValue.value) / nPrice;\n domCoin.value = nValue <= 0 ? '' : nValue;\n }\n}\n\nexport function toClipboard(source, caller) {\n // Fetch the text/value source\n const domCopy = document.getElementById(source) || source;\n\n // Use an invisible textbox as the clipboard source\n const domClipboard = document.getElementById('clipboard');\n domClipboard.value = domCopy.value || domCopy.innerHTML || domCopy;\n domClipboard.select();\n domClipboard.setSelectionRange(0, 99999);\n\n // Browser-dependent clipboard execution\n if (!navigator.clipboard) {\n document.execCommand('copy');\n } else {\n navigator.clipboard.writeText(domCopy.innerHTML || domCopy);\n }\n\n // Display a temporary checkmark response\n caller.classList.add('fa-check');\n caller.classList.remove('fa-clipboard');\n caller.style.cursor = 'default';\n setTimeout(() => {\n caller.classList.add('fa-clipboard');\n caller.classList.remove('fa-check');\n caller.style.cursor = 'pointer';\n }, 1000);\n}\n\n/**\n * Prompt for a payment in the GUI with pre-filled inputs\n * @param {string} strTo - The address receiving the payment\n * @param {number} nAmount - The payment amount in full coins\n * @param {string} strDesc - The payment message or description\n */\nexport function guiPreparePayment(strTo = '', nAmount = 0, strDesc = '') {\n // Apply values\n doms.domAddress1s.value = strTo;\n doms.domSendAmountCoins.value = nAmount;\n doms.domReqDesc.value = strDesc;\n doms.domReqDisplay.style.display = strDesc ? 'block' : 'none';\n\n // Switch to the Dashboard\n doms.domDashboard.click();\n\n // Open the Send menu, if not already open (with a small timeout post-load to allow for CSS loading)\n if (\n document\n .getElementById('transferMenu')\n .classList.contains('transferAnimation')\n ) {\n setTimeout(() => {\n toggleBottomMenu('transferMenu', 'transferAnimation');\n }, 300);\n }\n\n // Update the conversion value\n updateAmountInputPair(\n doms.domSendAmountCoins,\n doms.domSendAmountValue,\n true\n );\n\n // Run the Input Validity checker\n guiCheckRecipientInput({ target: doms.domAddress1s });\n\n // Focus on the coin input box (if no pre-fill was specified)\n if (nAmount <= 0) {\n doms.domSendAmountCoins.focus();\n }\n}\n\n/**\n * Set the \"Wallet Options\" menu visibility\n * @param {String} strDisplayCSS - The `display` CSS option to set the Wallet Options to\n */\nexport function setDisplayForAllWalletOptions(strDisplayCSS) {\n // Set the display and Reset the Vanity address input\n doms.domPrefix.value = '';\n doms.domPrefix.style.display = strDisplayCSS;\n\n // Set all \"*Wallet\" buttons\n doms.domGenerateWallet.style.display = strDisplayCSS;\n doms.domImportWallet.style.display = strDisplayCSS;\n doms.domGenVanityWallet.style.display = strDisplayCSS;\n doms.domAccessWallet.style.display = strDisplayCSS;\n doms.domGenHardwareWallet.style.display = strDisplayCSS;\n}\n\nexport async function govVote(hash, voteCode) {\n if (\n (await confirmPopup({\n title: ALERTS.CONFIRM_POPUP_VOTE,\n html: ALERTS.CONFIRM_POPUP_VOTE_HTML,\n })) == true\n ) {\n const database = await Database.getInstance();\n const cMasternode = await database.getMasternode();\n if (cMasternode) {\n if ((await cMasternode.getStatus()) !== 'ENABLED') {\n createAlert('warning', ALERTS.MN_NOT_ENABLED, 6000);\n return;\n }\n const result = await cMasternode.vote(hash.toString(), voteCode); //1 yes 2 no\n if (result.includes('Voted successfully')) {\n //good vote\n cMasternode.storeVote(hash.toString(), voteCode);\n await updateGovernanceTab();\n createAlert('success', ALERTS.VOTE_SUBMITTED, 6000);\n } else if (result.includes('Error voting :')) {\n //If you already voted return an alert\n createAlert('warning', ALERTS.VOTED_ALREADY, 6000);\n } else if (result.includes('Failure to verify signature.')) {\n //wrong masternode private key\n createAlert('warning', ALERTS.VOTE_SIG_BAD, 6000);\n } else {\n //this could be everything\n console.error(result);\n createAlert('warning', ALERTS.INTERNAL_ERROR, 6000);\n }\n } else {\n createAlert('warning', ALERTS.MN_ACCESS_BEFORE_VOTE, 6000);\n }\n }\n}\n\n/**\n * Start a Masternode via a signed network broadcast\n * @param {boolean} fRestart - Whether this is a Restart or a first Start\n */\nexport async function startMasternode(fRestart = false) {\n const database = await Database.getInstance();\n const cMasternode = await database.getMasternode(masterKey);\n if (cMasternode) {\n if (\n masterKey.isViewOnly &&\n !(await restoreWallet(translation.walletUnlockMNStart))\n )\n return;\n if (await cMasternode.start()) {\n const strMsg = fRestart ? ALERTS.MN_RESTARTED : ALERTS.MN_STARTED;\n createAlert('success', strMsg, 4000);\n } else {\n const strMsg = fRestart\n ? ALERTS.MN_RESTART_FAILED\n : ALERTS.MN_START_FAILED;\n createAlert('warning', strMsg, 4000);\n }\n }\n}\n\nexport async function destroyMasternode() {\n const database = await Database.getInstance();\n\n if (await database.getMasternode(masterKey)) {\n database.removeMasternode(masterKey);\n createAlert('success', ALERTS.MN_DESTROYED, 5000);\n updateMasternodeTab();\n }\n}\n\n/**\n * Takes an ip address and adds the port.\n * If it's a tor address, ip.onion:port will be used (e.g. expyuzz4wqqyqhjn.onion:12345)\n * If it's an IPv4 address, ip:port will be used, (e.g. 127.0.0.1:12345)\n * If it's an IPv6 address, [ip]:port will be used, (e.g. [::1]:12345)\n * @param {String} ip - Ip address with or without port\n * @returns {String}\n */\nfunction parseIpAddress(ip) {\n // IPv4 or tor without port\n if (ip.match(/\\d+\\.\\d+\\.\\d+\\.\\d+/) || ip.match(/\\w+\\.onion/)) {\n return `${ip}:${cChainParams.current.MASTERNODE_PORT}`;\n }\n\n // IPv4 or tor with port\n if (ip.match(/\\d+\\.\\d+\\.\\d+\\.\\d+:\\d+/) || ip.match(/\\w+\\.onion:\\d+/)) {\n return ip;\n }\n\n // IPv6 without port\n if (Address6.isValid(ip)) {\n return `[${ip}]:${cChainParams.current.MASTERNODE_PORT}`;\n }\n\n const groups = /\\[(.*)\\]:\\d+/.exec(ip);\n if (groups !== null && groups.length > 1) {\n // IPv6 with port\n if (Address6.isValid(groups[1])) {\n return ip;\n }\n }\n\n // If we haven't returned yet, the address was invalid.\n return null;\n}\n\nexport async function importMasternode() {\n const mnPrivKey = doms.domMnPrivateKey.value;\n const address = parseIpAddress(doms.domMnIP.value);\n if (!address) {\n createAlert('warning', ALERTS.MN_BAD_IP, 5000);\n return;\n }\n\n let collateralTxId;\n let outidx;\n let collateralPrivKeyPath;\n doms.domMnIP.value = '';\n doms.domMnPrivateKey.value = '';\n\n if (!masterKey.isHD) {\n // Find the first UTXO matching the expected collateral size\n const cCollaUTXO = mempool\n .getConfirmed()\n .find(\n (cUTXO) => cUTXO.sats === cChainParams.current.collateralInSats\n );\n\n // If there's no valid UTXO, exit with a contextual message\n if (!cCollaUTXO) {\n if (getBalance(false) < cChainParams.current.collateralInSats) {\n // Not enough balance to create an MN UTXO\n const amount =\n (cChainParams.current.collateralInSats -\n getBalance(false)) /\n COIN;\n const ticker = cChainParams.current.TICKER;\n createAlert(\n 'warning',\n tr(ALERTS.MN_NOT_ENOUGH_COLLAT, [\n { amount: amount },\n { ticker: ticker },\n ]),\n 10000\n );\n } else {\n // Balance is capable of a masternode, just needs to be created\n // TODO: this UX flow is weird, is it even possible? perhaps we can re-design this entire function accordingly\n const amount = cChainParams.current.collateralInSats / COIN;\n const ticker = cChainParams.current.TICKER;\n createAlert(\n 'warning',\n tr(ALERTS.MN_ENOUGH_BUT_NO_COLLAT, [\n { amount },\n { ticker },\n ]),\n 10000\n );\n }\n return;\n }\n\n collateralTxId = cCollaUTXO.id;\n outidx = cCollaUTXO.vout;\n collateralPrivKeyPath = 'legacy';\n } else {\n const path = doms.domMnTxId.value;\n const masterUtxo = mempool\n .getConfirmed()\n .findLast((u) => u.path === path); // first UTXO for each address in HD\n // sanity check:\n if (masterUtxo.sats !== cChainParams.current.collateralInSats) {\n return createAlert('warning', ALERTS.MN_COLLAT_NOT_SUITABLE, 10000);\n }\n collateralTxId = masterUtxo.id;\n outidx = masterUtxo.vout;\n collateralPrivKeyPath = path;\n }\n doms.domMnTxId.value = '';\n\n const cMasternode = new Masternode({\n walletPrivateKeyPath: collateralPrivKeyPath,\n mnPrivateKey: mnPrivKey,\n collateralTxId: collateralTxId,\n outidx: outidx,\n addr: address,\n });\n await refreshMasternodeData(cMasternode, true);\n await updateMasternodeTab();\n}\n\nexport async function accessOrImportWallet() {\n // Hide and Reset the Vanity address input\n doms.domPrefix.value = '';\n doms.domPrefix.style.display = 'none';\n\n // Show Import button, hide access button\n doms.domImportWallet.style.display = 'block';\n setTimeout(() => {\n doms.domPrivKey.style.opacity = '1';\n }, 100);\n doms.domAccessWalletBtn.style.display = 'none';\n\n // If we have a local wallet, display the decryption prompt\n // This is no longer being used, as the user will be put in view-only\n // mode when logging in, however if the user locked the wallet before\n // #52 there would be no way to recover the public key without getting\n // The password from the user\n if (await hasEncryptedWallet()) {\n doms.domPrivKey.placeholder = translation.encryptPasswordFirst;\n doms.domImportWalletText.innerText = translation.unlockWallet;\n doms.domPrivKey.focus();\n }\n}\n/**\n * An event function triggered apon private key UI input changes\n *\n * Useful for adjusting the input types or displaying password prompts depending on the import scheme\n */\nexport async function onPrivateKeyChanged() {\n if (await hasEncryptedWallet()) return;\n // Check whether the string is Base64 (would likely be an MPW-encrypted import)\n // and it doesn't have any spaces (would be a mnemonic seed)\n const fContainsSpaces = doms.domPrivKey.value.includes(' ');\n doms.domPrivKeyPassword.hidden =\n (doms.domPrivKey.value.length < 128 ||\n !isBase64(doms.domPrivKey.value)) &&\n !fContainsSpaces;\n\n doms.domPrivKeyPassword.placeholder = fContainsSpaces\n ? translation.optionalPassphrase\n : translation.password;\n // Uncloak the private input IF spaces are detected, to make Seed Phrases easier to input and verify\n doms.domPrivKey.setAttribute('type', fContainsSpaces ? 'text' : 'password');\n}\n\n/**\n * Imports a wallet using the GUI input, handling decryption via UI\n */\nexport async function guiImportWallet() {\n // Important: These fields will be wiped by importWallet();\n const strPrivKey = doms.domPrivKey.value;\n const strPassword = doms.domPrivKeyPassword.value;\n const fEncrypted = strPrivKey.length >= 128 && isBase64(strPrivKey);\n\n // If we are in testnet: prompt an import\n if (cChainParams.current.isTestnet) return importWallet();\n\n // If we don't have a DB wallet and the input is plain: prompt an import\n if (!(await hasEncryptedWallet()) && !fEncrypted) return importWallet();\n\n // If we don't have a DB wallet and the input is ciphered:\n if (!(await hasEncryptedWallet()) && fEncrypted) {\n const strDecWIF = await decrypt(strPrivKey, strPassword);\n if (!strDecWIF || strDecWIF === 'decryption failed!') {\n return createAlert('warning', ALERTS.FAILED_TO_IMPORT, 6000);\n } else {\n await importWallet({\n newWif: strDecWIF,\n // Save the public key to disk for future View Only mode post-decryption\n fSavePublicKey: true,\n });\n\n if (masterKey) {\n // Prepare a new Account to add\n const cAccount = new Account({\n publicKey: await masterKey.keyToExport,\n encWif: strPrivKey,\n });\n\n // Add the new Account to the DB\n const database = await Database.getInstance();\n database.addAccount(cAccount);\n }\n\n // Destroy residue import data\n doms.domPrivKey.value = '';\n doms.domPrivKeyPassword.value = '';\n return;\n }\n }\n // Prompt for decryption of the existing wallet\n const fHasWallet = await decryptWallet(doms.domPrivKey.value);\n\n // If the wallet was successfully loaded, hide all options and load the dash!\n if (fHasWallet) setDisplayForAllWalletOptions('none');\n}\n\nexport async function guiEncryptWallet() {\n // Fetch our inputs, ensure they're of decent entropy + match eachother\n const strPass = doms.domEncryptPasswordFirst.value,\n strPassRetype = doms.domEncryptPasswordSecond.value;\n if (strPass.length < MIN_PASS_LENGTH)\n return createAlert(\n 'warning',\n tr(ALERTS.PASSWORD_TOO_SMALL, [\n { MIN_PASS_LENGTH: MIN_PASS_LENGTH },\n ]),\n 4000\n );\n if (strPass !== strPassRetype)\n return createAlert('warning', ALERTS.PASSWORD_DOESNT_MATCH, 2250);\n\n // If this wallet is already encrypted, then we'll check for the current password and ensure it decrypts properly too\n if (await hasEncryptedWallet()) {\n // Grab the pass, and wipe the dialog immediately\n const strCurrentPass = doms.domEncryptPasswordCurrent.value;\n doms.domEncryptPasswordCurrent.value = '';\n\n // If the decryption fails: we don't allow changing the password\n if (!(await decryptWallet(strCurrentPass))) return;\n }\n\n // Encrypt the wallet using the new password\n await encryptWallet(strPass);\n createAlert('success', ALERTS.NEW_PASSWORD_SUCCESS, 5500);\n\n // Hide and reset the encryption modal\n $('#encryptWalletModal').modal('hide');\n doms.domEncryptPasswordFirst.value = '';\n doms.domEncryptPasswordSecond.value = '';\n\n // Display the 'Unlock/Lock Wallet' buttons accordingly based on state\n doms.domWipeWallet.hidden = masterKey.isViewOnly;\n doms.domRestoreWallet.hidden = !masterKey.isViewOnly;\n\n // Update the encryption UI (changes to \"Change Password\" now)\n await updateEncryptionGUI(true);\n}\n\n/** Update the \"Encrypt Wallet\" / \"Change Password\" dialog to match the current wallet state */\nexport async function updateEncryptionGUI(fEncrypted = null) {\n // If no param is provided, check if a wallet exists in the database\n if (fEncrypted === null) {\n fEncrypted = await hasEncryptedWallet();\n }\n // If the wallet is encrypted, we display a \"Current Password\" input in the Encryption dialog, otherwise, only accept New Passwords\n doms.domEncryptPasswordCurrent.style.display = fEncrypted ? '' : 'none';\n // And we adjust the displays to accomodate the mode as well\n doms.domEncryptWalletLabel.innerText = fEncrypted\n ? translation.changePassword\n : translation.encryptWallet;\n doms.domChangePasswordContainer.style.display = fEncrypted ? '' : 'none';\n}\n\nexport async function toggleExportUI() {\n if (!exportHidden) {\n if (await hasEncryptedWallet()) {\n const { encWif } = await (\n await Database.getInstance()\n ).getAccount();\n doms.domExportPrivateKey.innerHTML = encWif;\n exportHidden = true;\n } else {\n if (masterKey.isViewOnly) {\n exportHidden = false;\n } else {\n doms.domExportPrivateKey.innerHTML = masterKey.keyToBackup;\n exportHidden = true;\n }\n }\n } else {\n doms.domExportPrivateKey.innerHTML = '';\n exportHidden = false;\n }\n}\n\nexport function checkVanity() {\n var e = event || window.event; // get event object\n var key = e.keyCode || e.which; // get key cross-browser\n var char = String.fromCharCode(key).trim(); // convert key to char\n if (char.length == 0) return;\n\n // Ensure the input is base58 compatible\n if (!MAP_B58.toLowerCase().includes(char.toLowerCase())) {\n if (e.preventDefault) e.preventDefault();\n e.returnValue = false;\n return createAlert(\n 'warning',\n tr(ALERTS.UNSUPPORTED_CHARACTER, [{ char: char }]),\n 3500\n );\n }\n}\n\nlet isVanityGenerating = false;\nconst arrWorkers = [];\nlet vanUiUpdater;\n\nfunction stopSearch() {\n isVanityGenerating = false;\n for (let thread of arrWorkers) {\n thread.terminate();\n }\n while (arrWorkers.length) arrWorkers.pop();\n doms.domPrefix.disabled = false;\n doms.domVanityUiButtonTxt.innerText = translation.dCardTwoButton;\n clearInterval(vanUiUpdater);\n}\n\nexport async function generateVanityWallet() {\n if (isVanityGenerating) return stopSearch();\n if (typeof Worker === 'undefined')\n return createAlert('error', ALERTS.UNSUPPORTED_WEBWORKERS, 7500);\n // Generate a vanity address with the given prefix\n if (\n doms.domPrefix.value.length === 0 ||\n doms.domPrefix.style.display === 'none'\n ) {\n // No prefix, display the intro!\n doms.domPrefix.style.display = 'block';\n setTimeout(() => {\n doms.domPrefix.style.opacity = '1';\n }, 100);\n doms.domPrefix.focus();\n } else {\n // Remove spaces from prefix\n doms.domPrefix.value = doms.domPrefix.value.replace(/ /g, '');\n\n // Cache a lowercase equivilent for lower-entropy comparisons (a case-insensitive search is ALOT faster!) and strip accidental spaces\n const nInsensitivePrefix = doms.domPrefix.value.toLowerCase();\n const nPrefixLen = nInsensitivePrefix.length;\n\n // Ensure the input is base58 compatible\n for (const char of doms.domPrefix.value) {\n if (!MAP_B58.toLowerCase().includes(char.toLowerCase()))\n return createAlert(\n 'warning',\n tr(ALERTS.UNSUPPORTED_CHARACTER, [{ char: char }]),\n 3500\n );\n // We also don't want users to be mining addresses for years... so cap the letters to four until the generator is more optimized\n if (doms.domPrefix.value.length > 5)\n return createAlert(\n 'warning',\n tr(ALERTS.UNSUPPORTED_CHARACTER, [{ char: char }]),\n 3500\n );\n }\n isVanityGenerating = true;\n doms.domPrefix.disabled = true;\n let attempts = 0;\n\n // Setup workers\n const nThreads = Math.max(\n Math.floor(window.navigator.hardwareConcurrency * 0.75),\n 1\n );\n console.log('Spawning ' + nThreads + ' vanity search threads!');\n while (arrWorkers.length < nThreads) {\n arrWorkers.push(\n new Worker(new URL('./vanitygen_worker.js', import.meta.url))\n );\n const checkResult = (data) => {\n attempts++;\n if (\n data.pub.substr(1, nPrefixLen).toLowerCase() ==\n nInsensitivePrefix\n ) {\n importWallet({\n newWif: data.priv,\n fRaw: true,\n });\n stopSearch();\n doms.domGuiBalance.innerHTML = '0';\n return console.log(\n 'VANITY: Found an address after ' +\n attempts +\n ' attempts!'\n );\n }\n };\n\n arrWorkers[arrWorkers.length - 1].onmessage = (event) =>\n checkResult(event.data);\n arrWorkers[arrWorkers.length - 1].postMessage(\n cChainParams.current.PUBKEY_ADDRESS\n );\n }\n\n // GUI Updater\n doms.domVanityUiButtonTxt.innerText =\n 'Stop (Searched ' + attempts.toLocaleString('en-GB') + ' keys)';\n vanUiUpdater = setInterval(() => {\n doms.domVanityUiButtonTxt.innerText =\n 'Stop (Searched ' + attempts.toLocaleString('en-GB') + ' keys)';\n }, 200);\n }\n}\n\n/**\n * Sweep an address to our own wallet, spending all it's UTXOs without change\n * @param {Array} arrUTXOs - The UTXOs belonging to the address to sweep\n * @param {LegacyMasterKey} sweepingMasterKey - The address to sweep from\n * @param {number} nFixedFee - An optional fixed satoshi fee\n * @returns {Promise} - TXID on success, false or error on failure\n */\nexport async function sweepAddress(arrUTXOs, sweepingMasterKey, nFixedFee = 0) {\n const cTx = new bitjs.transaction();\n\n // Load all UTXOs as inputs\n let nTotal = 0;\n for (const cUTXO of arrUTXOs) {\n nTotal += cUTXO.sats;\n cTx.addinput({\n txid: cUTXO.id,\n index: cUTXO.vout,\n script: cUTXO.script,\n path: cUTXO.path,\n });\n }\n\n // Use a given fixed fee, or use the network fee if unspecified\n const nFee = nFixedFee || getNetwork().getFee(cTx.serialize().length);\n\n // Use a new address from our wallet to sweep the UTXOs in to\n const strAddress = (await getNewAddress(true, false))[0];\n\n // Sweep the full funds amount, minus the fee, leaving no change from any sweeped UTXOs\n cTx.addoutput(strAddress, (nTotal - nFee) / COIN);\n\n // Sign using the given Master Key, then broadcast the sweep, returning the TXID (or a failure)\n const sign = await signTransaction(cTx, sweepingMasterKey);\n return await getNetwork().sendTransaction(sign);\n}\n\nexport function toggleDropDown(id) {\n const domID = document.getElementById(id);\n domID.style.display = domID.style.display === 'block' ? 'none' : 'block';\n}\n\nexport function isMasternodeUTXO(cUTXO, cMasternode) {\n if (cMasternode?.collateralTxId) {\n const { collateralTxId, outidx } = cMasternode;\n return collateralTxId === cUTXO.id && cUTXO.vout === outidx;\n } else {\n return false;\n }\n}\n\n/**\n * Creates a GUI popup for the user to check or customise their Cold Address\n */\nexport async function guiSetColdStakingAddress() {\n if (\n await confirmPopup({\n title: translation.popupSetColdAddr,\n html: `

${\n translation.popupCurrentAddress\n }
${strColdStakingAddress}

${\n translation.popupColdStakeNote\n }


`,\n })\n ) {\n // Fetch address from the popup input\n const strColdAddress = document.getElementById('newColdAddress').value;\n\n // If it's empty, just return false\n if (!strColdAddress) return false;\n\n // Sanity-check, and set!\n if (\n strColdAddress[0] === cChainParams.current.STAKING_PREFIX &&\n strColdAddress.length === 34\n ) {\n await setColdStakingAddress(strColdAddress);\n createAlert('info', ALERTS.STAKE_ADDR_SET, 5000);\n return true;\n } else {\n createAlert('warning', ALERTS.STAKE_ADDR_BAD, 2500);\n return false;\n }\n } else {\n return false;\n }\n}\n\nexport async function wipePrivateData() {\n const isEncrypted = await hasEncryptedWallet();\n const title = isEncrypted\n ? translation.popupWalletLock\n : translation.popupWalletWipe;\n const html = isEncrypted\n ? translation.popupWalletLockNote\n : translation.popupWalletWipeNote;\n if (\n await confirmPopup({\n title,\n html,\n })\n ) {\n masterKey.wipePrivateData();\n doms.domWipeWallet.hidden = true;\n if (isEncrypted) {\n doms.domRestoreWallet.hidden = false;\n }\n }\n}\n\n/**\n * Prompt the user in the GUI to unlock their wallet\n * @param {string} strReason - An optional reason for the unlock\n * @returns {Promise} - If the unlock was successful or rejected\n */\nexport async function restoreWallet(strReason = '') {\n // Build up the UI elements based upon conditions for the unlock prompt\n let strHTML = '';\n\n // If there's a reason given; display it as a sub-text\n strHTML += `

${strReason}

`;\n\n // Prompt the user\n if (\n await confirmPopup({\n title: translation.walletUnlock,\n html: `${strHTML}`,\n })\n ) {\n // Fetch the password from the prompt, and immediately destroy the prompt input\n const domPassword = document.getElementById('restoreWalletPassword');\n const strPassword = domPassword.value;\n domPassword.value = '';\n\n // Attempt to unlock the wallet with the provided password\n if (await decryptWallet(strPassword)) {\n doms.domRestoreWallet.hidden = true;\n doms.domWipeWallet.hidden = false;\n // Wallet is unlocked!\n return true;\n } else {\n // Password is invalid\n return false;\n }\n } else {\n // User rejected the unlock\n return false;\n }\n}\n\n/** A lock to prevent rendering the Governance Dashboard multiple times */\nlet fRenderingGovernance = false;\n\n/**\n * Fetch Governance data and re-render the Governance UI\n */\nexport async function updateGovernanceTab() {\n if (fRenderingGovernance) return;\n fRenderingGovernance = true;\n\n // Setup the Superblock countdown (if not already done), no need to block thread with await, either.\n let cNet = getNetwork();\n\n // When switching to mainnet from testnet or vise versa, you ned to use an await on getBlockCount() or cNet.cachedBlockCount returns 0\n if (!isTestnetLastState == cChainParams.current.isTestnet) {\n // Reset flipdown\n governanceFlipdown = null;\n doms.domFlipdown.innerHTML = '';\n\n // Get new network blockcount\n await getNetwork().getBlockCount();\n cNet = getNetwork();\n }\n\n // Update governance counter when testnet/mainnet has been switched\n if (!governanceFlipdown && cNet.cachedBlockCount > 0) {\n Masternode.getNextSuperblock().then((nSuperblock) => {\n // The estimated time to the superblock (using the block target and remaining blocks)\n const nTimestamp =\n Date.now() / 1000 + (nSuperblock - cNet.cachedBlockCount) * 60;\n governanceFlipdown = new FlipDown(nTimestamp).start();\n });\n isTestnetLastState = cChainParams.current.isTestnet;\n }\n\n // Fetch all proposals from the network\n const arrProposals = await Masternode.getProposals({\n fAllowFinished: false,\n });\n\n /* Sort proposals into two categories\n - Standard (Proposal is either new with <100 votes, or has a healthy vote count)\n - Contested (When a proposal may be considered spam, malicious, or simply highly contestable)\n */\n const arrStandard = arrProposals.filter(\n (a) => a.Yeas + a.Nays < 100 || a.Ratio > 0.25\n );\n const arrContested = arrProposals.filter(\n (a) => a.Yeas + a.Nays >= 100 && a.Ratio <= 0.25\n );\n\n // Render Proposals\n await Promise.all([\n renderProposals(arrStandard, false),\n renderProposals(arrContested, true),\n ]);\n\n // Remove lock\n fRenderingGovernance = false;\n}\n\n/**\n * @typedef {Object} ProposalCache\n * @property {number} nSubmissionHeight - The submission height of the proposal.\n * @property {string} txid - The transaction ID of the proposal (string).\n * @property {boolean} fFetching - Indicates whether the proposal is currently being fetched or not.\n */\n\n/**\n * An array of Proposal Finalisation caches\n * @type {Array}\n */\nconst arrProposalFinalisationCache = [];\n\n/**\n * Asynchronously wait for a Proposal Tx to confirm, then cache the height.\n *\n * Do NOT await unless you want to lock the thread for a long time.\n * @param {ProposalCache} cProposalCache - The proposal cache to wait for\n * @returns {Promise} Returns `true` once the block height is cached\n */\nasync function waitForSubmissionBlockHeight(cProposalCache) {\n let nHeight = null;\n\n // Wait in a permanent throttled loop until we successfully fetch the block\n const cNet = getNetwork();\n while (true) {\n // If a proposal is already fetching, then consequtive calls will be rejected\n cProposalCache.fFetching = true;\n\n // Attempt to fetch the submission Tx (may not exist yet!)\n let cTx = null;\n try {\n cTx = await cNet.getTxInfo(cProposalCache.txid);\n } catch (_) {}\n\n if (!cTx || !cTx.blockHeight) {\n // Didn't get the TX, throttle the thread by sleeping for a bit, then try again.\n await sleep(30000);\n } else {\n nHeight = cTx.blockHeight;\n break;\n }\n }\n\n // Update the proposal finalisation cache\n cProposalCache.nSubmissionHeight = nHeight;\n\n return true;\n}\n\n/**\n * Create a Status String for a proposal's finalisation status\n * @param {ProposalCache} cPropCache - The proposal cache to check\n * @returns {string} The string status, for display purposes\n */\nfunction getProposalFinalisationStatus(cPropCache) {\n const cNet = getNetwork();\n const nConfsLeft = cPropCache.nSubmissionHeight + 6 - cNet.cachedBlockCount;\n\n if (cPropCache.nSubmissionHeight === 0 || cNet.cachedBlockCount === 0) {\n return translation.proposalFinalisationConfirming;\n } else if (nConfsLeft > 0) {\n return (\n nConfsLeft +\n ' block' +\n (nConfsLeft === 1 ? '' : 's') +\n ' ' +\n translation.proposalFinalisationRemaining\n );\n } else if (Math.abs(nConfsLeft) >= cChainParams.current.budgetCycleBlocks) {\n return translation.proposalFinalisationExpired;\n } else {\n return translation.proposalFinalisationReady;\n }\n}\n\n/**\n *\n * @param {Object} cProposal - A local proposal to add to the cache tracker\n * @returns {ProposalCache} - The finalisation cache object pointer of the local proposal\n */\nfunction addProposalToFinalisationCache(cProposal) {\n // If it exists, return the existing cache\n /** @type ProposalCache */\n let cPropCache = arrProposalFinalisationCache.find(\n (a) => a.txid === cProposal.mpw.txid\n );\n if (cPropCache) return cPropCache;\n\n // Create a new cache\n cPropCache = {\n nSubmissionHeight: 0,\n txid: cProposal.mpw.txid,\n fFetching: false,\n };\n arrProposalFinalisationCache.push(cPropCache);\n\n // Return the object 'pointer' in the array for further updating\n return cPropCache;\n}\n\n/**\n * Render Governance proposal objects to a given Proposal category\n * @param {Array} arrProposals - The proposals to render\n * @param {boolean} fContested - The proposal category\n */\nasync function renderProposals(arrProposals, fContested) {\n // Set the total budget\n doms.domTotalGovernanceBudget.innerText = (\n cChainParams.current.maxPayment / COIN\n ).toLocaleString('en-gb');\n\n // Update total budget in user's currency\n const nPrice = await cMarket.getPrice(strCurrency);\n const nCurrencyValue = (cChainParams.current.maxPayment / COIN) * nPrice;\n const { nValue, cLocale } = optimiseCurrencyLocale(nCurrencyValue);\n doms.domTotalGovernanceBudgetValue.innerHTML =\n nValue.toLocaleString('en-gb', cLocale) +\n ' ' +\n strCurrency.toUpperCase() +\n '';\n\n // Select the table based on the proposal category\n const domTable = fContested\n ? doms.domGovProposalsContestedTableBody\n : doms.domGovProposalsTableBody;\n\n // Render the proposals in the relevent table\n const database = await Database.getInstance();\n const cMasternode = await database.getMasternode();\n\n if (!fContested) {\n const localProposals =\n (await database.getAccount())?.localProposals?.map((p) => {\n return {\n Name: p.name,\n URL: p.url,\n PaymentAddress: p.address,\n MonthlyPayment: p.monthlyPayment / COIN,\n RemainingPaymentCount: p.nPayments,\n TotalPayment: p.nPayments * (p.monthlyPayment / COIN),\n Yeas: 0,\n Nays: 0,\n local: true,\n Ratio: 0,\n mpw: p,\n };\n }) || [];\n arrProposals = localProposals.concat(arrProposals);\n }\n arrProposals = await Promise.all(\n arrProposals.map(async (p) => {\n return {\n YourVote:\n cMasternode && p.Hash\n ? await cMasternode.getVote(p.Name, p.Hash)\n : null,\n ...p,\n };\n })\n );\n\n // Fetch the Masternode count for proposal status calculations\n const cMasternodes = await Masternode.getMasternodeCount();\n\n let totalAllocatedAmount = 0;\n\n // Wipe the current table and start rendering proposals\n let i = 0;\n domTable.innerHTML = '';\n for (const cProposal of arrProposals) {\n const domRow = domTable.insertRow();\n\n const domStatus = domRow.insertCell();\n domStatus.classList.add('governStatusCol');\n if (domTable.id == 'proposalsTableBody') {\n domStatus.setAttribute(\n 'onclick',\n `if(document.getElementById('governMob${i}').classList.contains('d-none')) { document.getElementById('governMob${i}').classList.remove('d-none'); } else { document.getElementById('governMob${i}').classList.add('d-none'); }`\n );\n } else if (domTable.id == 'proposalsContestedTableBody') {\n domStatus.setAttribute(\n 'onclick',\n `if(document.getElementById('governMobCon${i}').classList.contains('d-none')) { document.getElementById('governMobCon${i}').classList.remove('d-none'); } else { document.getElementById('governMobCon${i}').classList.add('d-none'); }`\n );\n }\n\n // Add border radius to last row\n if (arrProposals.length - 1 == i) {\n domStatus.classList.add('bblr-7p');\n }\n\n // Net Yes calculation\n const { Yeas, Nays } = cProposal;\n const nNetYes = Yeas - Nays;\n const nNetYesPercent = (nNetYes / cMasternodes.enabled) * 100;\n\n // Proposal Status calculation\n const nRequiredVotes = Math.round(cMasternodes.enabled * 0.1);\n const strStatus =\n nNetYes >= nRequiredVotes\n ? translation.proposalPassing\n : translation.proposalFailing;\n let strFundingStatus = translation.proposalNotFunded;\n\n // Funding Status and allocation calculations\n if (cProposal.local) {\n // Check the finalisation cache\n const cPropCache = addProposalToFinalisationCache(cProposal);\n if (!cPropCache.fFetching) {\n waitForSubmissionBlockHeight(cPropCache).then(\n updateGovernanceTab\n );\n }\n const strStatus = getProposalFinalisationStatus(cPropCache);\n const finalizeButton = document.createElement('button');\n finalizeButton.className = 'pivx-button-small';\n finalizeButton.innerHTML = '';\n\n if (\n strStatus === translation.proposalFinalisationReady ||\n strStatus === translation.proposalFinalisationExpired\n ) {\n finalizeButton.addEventListener('click', async () => {\n const result = await Masternode.finalizeProposal(\n cProposal.mpw\n );\n\n const deleteProposal = async () => {\n // Fetch Account\n const account = await database.getAccount();\n\n // Find index of Account local proposal to remove\n const nProposalIndex = account.localProposals.findIndex(\n (p) => p.txid === cProposal.mpw.txid\n );\n\n // If found, remove the proposal and update the account with the modified localProposals array\n if (nProposalIndex > -1) {\n // Remove our proposal from it\n account.localProposals.splice(nProposalIndex, 1);\n\n // Update the DB\n await database.updateAccount(account, true);\n }\n };\n\n if (result.ok) {\n deleteProposal();\n // Create a prompt showing the finalisation success, vote hash, and further details\n confirmPopup({\n title: translation.PROPOSAL_FINALISED + ' 🚀',\n html: `

${\n translation.popupProposalFinalisedNote\n }

${\n translation.popupProposalVoteHash\n }
${sanitizeHTML(\n result.hash\n )}

${\n translation.popupProposalFinalisedSignoff\n } 👋

`,\n hideConfirm: true,\n });\n updateGovernanceTab();\n } else {\n if (result.err === 'unconfirmed') {\n createAlert(\n 'warning',\n ALERTS.PROPOSAL_UNCONFIRMED,\n 5000\n );\n } else if (result.err === 'invalid') {\n createAlert(\n 'warning',\n ALERTS.PROPOSAL_EXPIRED,\n 5000\n );\n deleteProposal();\n updateGovernanceTab();\n } else {\n createAlert(\n 'warning',\n ALERTS.PROPOSAL_FINALISE_FAIL\n );\n }\n }\n });\n } else {\n finalizeButton.style.opacity = 0.5;\n finalizeButton.style.cursor = 'default';\n }\n\n domStatus.innerHTML = `\n \n ${strStatus}
\n
\n \n \n `;\n domStatus.appendChild(finalizeButton);\n } else {\n if (domTable.id == 'proposalsTableBody') {\n if (\n nNetYes >= nRequiredVotes &&\n totalAllocatedAmount + cProposal.MonthlyPayment <=\n cChainParams.current.maxPayment / COIN\n ) {\n strFundingStatus = translation.proposalFunded;\n totalAllocatedAmount += cProposal.MonthlyPayment;\n }\n }\n\n // Figure out the colour of the Status, if any (using CSS class `votes[Yes/No]`)\n const strColourClass =\n strStatus === translation.proposalPassing ? 'Yes' : 'No';\n\n domStatus.innerHTML = `\n \n ${strStatus}
\n (${strFundingStatus})
\n
\n \n ${nNetYesPercent.toFixed(1)}%
\n ${translation.proposalNetYes}\n
\n \n \n `;\n }\n\n // Name, Payment Address and URL hyperlink\n const domNameAndURL = domRow.insertCell();\n domNameAndURL.style = 'vertical-align: middle;';\n\n // IMPORTANT: Sanitise all of our HTML or a rogue server or malicious proposal could perform a cross-site scripting attack\n domNameAndURL.innerHTML = `${sanitizeHTML(\n cProposal.Name\n )}
${sanitizeHTML(\n cProposal.PaymentAddress.slice(0, 6) + '...'\n )}`;\n\n // Convert proposal amount to user's currency\n const nProposalValue = parseInt(cProposal.MonthlyPayment) * nPrice;\n const { nValue } = optimiseCurrencyLocale(nProposalValue);\n const strProposalCurrency = nValue.toLocaleString('en-gb', cLocale);\n\n // Payment Schedule and Amounts\n const domPayments = domRow.insertCell();\n domPayments.classList.add('for-desktop');\n domPayments.style = 'vertical-align: middle;';\n domPayments.innerHTML = `${sanitizeHTML(\n parseInt(cProposal.MonthlyPayment).toLocaleString('en-gb', ',', '.')\n )} ${\n cChainParams.current.TICKER\n }
\n (${strProposalCurrency} ${strCurrency.toUpperCase()})
\n\n ${sanitizeHTML(\n cProposal['RemainingPaymentCount']\n )} ${translation.proposalPaymentsRemaining} ${sanitizeHTML(\n parseInt(cProposal.TotalPayment).toLocaleString('en-gb', ',', '.')\n )} ${cChainParams.current.TICKER} ${\n translation.proposalPaymentTotal\n }`;\n\n // Vote Counts and Consensus Percentages\n const domVoteCounters = domRow.insertCell();\n domVoteCounters.classList.add('for-desktop');\n domVoteCounters.style = 'vertical-align: middle;';\n\n const nLocalPercent = cProposal.Ratio * 100;\n domVoteCounters.innerHTML = `${parseFloat(\n nLocalPercent\n ).toLocaleString(\n 'en-gb',\n { minimumFractionDigits: 0, maximumFractionDigits: 1 },\n ',',\n '.'\n )}%
\n
${sanitizeHTML(\n Yeas\n )}
/\n
${sanitizeHTML(\n Nays\n )}
\n `;\n\n // Voting Buttons for Masternode owners (MNOs)\n let voteBtn;\n if (cProposal.local) {\n const domVoteBtns = domRow.insertCell();\n domVoteBtns.classList.add('for-desktop');\n domVoteBtns.style = 'vertical-align: middle;';\n voteBtn = '';\n } else {\n let btnYesClass = 'pivx-button-small';\n let btnNoClass = 'pivx-button-small';\n if (cProposal.YourVote) {\n if (cProposal.YourVote === 1) {\n btnYesClass += ' pivx-button-big-yes-gov';\n } else {\n btnNoClass += ' pivx-button-big-no-gov';\n }\n }\n const domVoteBtns = domRow.insertCell();\n domVoteBtns.style = 'vertical-align: middle;';\n const domNoBtn = document.createElement('button');\n domNoBtn.className = btnNoClass;\n domNoBtn.innerText = translation.no;\n domNoBtn.onclick = () => govVote(cProposal.Hash, 2);\n\n const domYesBtn = document.createElement('button');\n domYesBtn.className = btnYesClass;\n domYesBtn.innerText = translation.yes;\n domYesBtn.onclick = () => govVote(cProposal.Hash, 1);\n\n // Add border radius to last row\n if (arrProposals.length - 1 == i) {\n domVoteBtns.classList.add('bbrr-7p');\n }\n\n domVoteBtns.classList.add('for-desktop');\n domVoteBtns.appendChild(domNoBtn);\n domVoteBtns.appendChild(domYesBtn);\n\n domNoBtn.setAttribute(\n 'onclick',\n `MPW.govVote('${cProposal.Hash}', 2)`\n );\n domYesBtn.setAttribute(\n 'onclick',\n `MPW.govVote('${cProposal.Hash}', 1);`\n );\n voteBtn = domNoBtn.outerHTML + domYesBtn.outerHTML;\n }\n\n // Create extended row for mobile\n const mobileDomRow = domTable.insertRow();\n const mobileExtended = mobileDomRow.insertCell();\n mobileExtended.style = 'vertical-align: middle;';\n if (domTable.id == 'proposalsTableBody') {\n mobileExtended.id = `governMob${i}`;\n } else if (domTable.id == 'proposalsContestedTableBody') {\n mobileExtended.id = `governMobCon${i}`;\n }\n mobileExtended.colSpan = '2';\n mobileExtended.classList.add('text-left');\n mobileExtended.classList.add('d-none');\n mobileExtended.classList.add('for-mobile');\n mobileExtended.innerHTML = `\n
\n
\n
${translation.govTablePayment}\n
\n
\n ${sanitizeHTML(\n parseInt(cProposal.MonthlyPayment).toLocaleString(\n 'en-gb',\n ',',\n '.'\n )\n )} ${\n cChainParams.current.TICKER\n } ${strProposalCurrency}\n \n ${sanitizeHTML(\n cProposal['RemainingPaymentCount']\n )} ${translation.proposalPaymentsRemaining} ${sanitizeHTML(\n parseInt(cProposal.TotalPayment).toLocaleString('en-gb', ',', '.')\n )} ${cChainParams.current.TICKER} ${\n translation.proposalPaymentTotal\n }\n
\n
\n
\n
\n
\n
${translation.govTableVotes}\n
\n
\n ${parseFloat(nLocalPercent).toLocaleString(\n 'en-gb',\n { minimumFractionDigits: 0, maximumFractionDigits: 1 },\n ',',\n '.'\n )}%\n
${sanitizeHTML(\n Yeas\n )}
/\n
${sanitizeHTML(\n Nays\n )}
\n
\n
\n
\n
\n
\n
${translation.govTableVote}\n
\n
\n ${voteBtn}\n
\n
`;\n\n i++;\n }\n\n // Show allocated budget\n if (domTable.id == 'proposalsTableBody') {\n const strAlloc = sanitizeHTML(\n totalAllocatedAmount.toLocaleString('en-gb')\n );\n doms.domAllocatedGovernanceBudget.innerHTML = strAlloc;\n doms.domAllocatedGovernanceBudget2.innerHTML = strAlloc;\n\n // Update allocated budget in user's currency\n const nCurrencyValue = totalAllocatedAmount * nPrice;\n const { nValue } = optimiseCurrencyLocale(nCurrencyValue);\n const strAllocCurrency =\n nValue.toLocaleString('en-gb', cLocale) +\n ' ' +\n strCurrency.toUpperCase() +\n '';\n doms.domAllocatedGovernanceBudgetValue.innerHTML = strAllocCurrency;\n doms.domAllocatedGovernanceBudgetValue2.innerHTML = strAllocCurrency;\n }\n}\n\nexport async function updateMasternodeTab() {\n //TODO: IN A FUTURE ADD MULTI-MASTERNODE SUPPORT BY SAVING MNs with which you logged in the past.\n // Ensure a wallet is loaded\n doms.domMnTextErrors.innerHTML = '';\n doms.domAccessMasternode.style.display = 'none';\n doms.domCreateMasternode.style.display = 'none';\n doms.domMnDashboard.style.display = 'none';\n\n if (!masterKey) {\n doms.domMnTextErrors.innerHTML =\n 'Please ' +\n ((await hasEncryptedWallet()) ? 'unlock' : 'import') +\n ' your COLLATERAL WALLET first.';\n return;\n }\n\n if (!mempool.getConfirmed().length) {\n doms.domMnTextErrors.innerHTML =\n 'Your wallet is empty or still loading, re-open the tab in a few seconds!';\n return;\n }\n\n const database = await Database.getInstance();\n\n let cMasternode = await database.getMasternode();\n // If the collateral is missing (spent, or switched wallet) then remove the current MN\n if (cMasternode) {\n if (\n !mempool\n .getConfirmed()\n .find((utxo) => isMasternodeUTXO(utxo, cMasternode))\n ) {\n database.removeMasternode();\n cMasternode = null;\n }\n }\n\n doms.domControlMasternode.style.display = cMasternode ? 'block' : 'none';\n\n // first case: the wallet is not HD and it is not hardware, so in case the wallet has collateral the user can check its status and do simple stuff like voting\n if (!masterKey.isHD) {\n doms.domMnAccessMasternodeText.innerHTML =\n doms.masternodeLegacyAccessText;\n doms.domMnTxId.style.display = 'none';\n // Find the first UTXO matching the expected collateral size\n const cCollaUTXO = mempool\n .getConfirmed()\n .find(\n (cUTXO) => cUTXO.sats === cChainParams.current.collateralInSats\n );\n const balance = getBalance(false);\n if (cCollaUTXO) {\n if (cMasternode) {\n await refreshMasternodeData(cMasternode);\n doms.domMnDashboard.style.display = '';\n } else {\n doms.domMnTxId.style.display = 'none';\n doms.domccessMasternode.style.display = 'block';\n }\n } else if (balance < cChainParams.current.collateralInSats) {\n // The user needs more funds\n doms.domMnTextErrors.innerHTML =\n 'You need ' +\n (cChainParams.current.collateralInSats - balance) / COIN +\n ' more ' +\n cChainParams.current.TICKER +\n ' to create a Masternode!';\n } else {\n // The user has the funds, but not an exact collateral, prompt for them to create one\n doms.domCreateMasternode.style.display = 'block';\n doms.domMnTxId.style.display = 'none';\n doms.domMnTxId.innerHTML = '';\n }\n } else {\n doms.domMnTxId.style.display = 'none';\n doms.domMnTxId.innerHTML = '';\n doms.domMnAccessMasternodeText.innerHTML = doms.masternodeHDAccessText;\n\n // First UTXO for each address in HD\n const mapCollateralAddresses = new Map();\n\n // Aggregate all valid Masternode collaterals into a map of Address <--> Collateral\n for (const cUTXO of mempool.getConfirmed()) {\n if (cUTXO.sats !== cChainParams.current.collateralInSats) continue;\n mapCollateralAddresses.set(cUTXO.path, cUTXO);\n }\n const fHasCollateral = mapCollateralAddresses.size > 0;\n\n // If there's no loaded MN, but valid collaterals, display the configuration screen\n if (!cMasternode && fHasCollateral) {\n doms.domMnTxId.style.display = 'block';\n doms.domAccessMasternode.style.display = 'block';\n\n for (const [key] of mapCollateralAddresses) {\n const option = document.createElement('option');\n option.value = key;\n option.innerText = await masterKey.getAddress(key);\n doms.domMnTxId.appendChild(option);\n }\n }\n\n // If there's no collateral found, display the creation UI\n if (!fHasCollateral) doms.domCreateMasternode.style.display = 'block';\n\n // If we have a collateral and a loaded Masternode, display the Dashboard\n if (fHasCollateral && cMasternode) {\n // Refresh the display\n refreshMasternodeData(cMasternode);\n doms.domMnDashboard.style.display = '';\n }\n }\n}\n\nasync function refreshMasternodeData(cMasternode, fAlert = false) {\n const cMasternodeData = await cMasternode.getFullData();\n if (debug) {\n console.log('---- NEW MASTERNODE DATA (Debug Mode) ----');\n console.log(cMasternodeData);\n console.log('---- END MASTERNODE DATA (Debug Mode) ----');\n }\n\n // If we have MN data available, update the dashboard\n if (cMasternodeData && cMasternodeData.status !== 'MISSING') {\n doms.domMnTextErrors.innerHTML = '';\n doms.domMnProtocol.innerText = `(${sanitizeHTML(\n cMasternodeData.version\n )})`;\n doms.domMnStatus.innerText = sanitizeHTML(cMasternodeData.status);\n doms.domMnNetType.innerText = sanitizeHTML(\n cMasternodeData.network.toUpperCase()\n );\n doms.domMnNetIP.innerText = cMasternode.addr;\n doms.domMnLastSeen.innerText = new Date(\n cMasternodeData.lastseen * 1000\n ).toLocaleTimeString();\n }\n\n if (cMasternodeData.status === 'MISSING') {\n doms.domMnTextErrors.innerHTML =\n 'Masternode is currently OFFLINE';\n if (!masterKey.isViewOnly) {\n createAlert('warning', ALERTS.MN_OFFLINE_STARTING, 6000);\n // try to start the masternode\n const started = await cMasternode.start();\n if (started) {\n doms.domMnTextErrors.innerHTML = ALERTS.MN_STARTED;\n createAlert('success', ALERTS.MN_STARTED_ONLINE_SOON, 6000);\n const database = await Database.getInstance();\n await database.addMasternode(cMasternode);\n } else {\n doms.domMnTextErrors.innerHTML = ALERTS.MN_START_FAILED;\n createAlert('warning', ALERTS.MN_START_FAILED, 6000);\n }\n }\n } else if (\n cMasternodeData.status === 'ENABLED' ||\n cMasternodeData.status === 'PRE_ENABLED'\n ) {\n if (fAlert)\n createAlert(\n 'success',\n `${ALERTS.MN_STATUS_IS} ${sanitizeHTML(\n cMasternodeData.status\n )} `,\n 6000\n );\n const database = await Database.getInstance();\n await database.addMasternode(cMasternode);\n } else if (cMasternodeData.status === 'REMOVED') {\n const state = cMasternodeData.status;\n doms.domMnTextErrors.innerHTML = tr(ALERTS.MN_STATE, [\n { state: state },\n ]);\n if (fAlert)\n createAlert(\n 'warning',\n tr(ALERTS.MN_STATE, [{ state: state }]),\n 6000\n );\n } else {\n // connection problem\n doms.domMnTextErrors.innerHTML = ALERTS.MN_CANT_CONNECT;\n if (fAlert) createAlert('warning', ALERTS.MN_CANT_CONNECT, 6000);\n }\n\n // Return the data in case the caller needs additional context\n return cMasternodeData;\n}\n\nexport async function createProposal() {\n if (!masterKey) {\n return createAlert('warning', ALERTS.PROPOSAL_IMPORT_FIRST);\n }\n if (\n masterKey.isViewOnly &&\n !(await restoreWallet(translation.walletUnlockProposal))\n ) {\n return;\n }\n if (getBalance() * COIN < cChainParams.current.proposalFee) {\n return createAlert('warning', ALERTS.PROPOSAL_NOT_ENOUGH_FUNDS);\n }\n\n const fConfirmed = await confirmPopup({\n title: `${translation.popupCreateProposal} (${\n translation.popupCreateProposalCost\n } ${cChainParams.current.proposalFee / COIN} ${\n cChainParams.current.TICKER\n })`,\n html: `
\n
\n
\n
`,\n });\n\n // If the user cancelled, then we return\n if (!fConfirmed) return;\n\n const strTitle = document.getElementById('proposalTitle').value;\n const strUrl = document.getElementById('proposalUrl').value;\n const numCycles = parseInt(document.getElementById('proposalCycles').value);\n const numPayment = parseInt(\n document.getElementById('proposalPayment').value\n );\n const nextSuperblock = await Masternode.getNextSuperblock();\n const proposal = {\n name: strTitle,\n url: strUrl,\n nPayments: numCycles,\n start: nextSuperblock,\n address: (await getNewAddress())[0],\n monthlyPayment: numPayment * COIN,\n };\n\n const isValid = Masternode.isValidProposal(proposal);\n if (!isValid.ok) {\n createAlert(\n 'warning',\n `${ALERTS.PROPOSAL_INVALID_ERROR} ${isValid.err}`,\n 5000\n );\n return;\n }\n\n const hash = Masternode.createProposalHash(proposal);\n const { ok, txid } = await createAndSendTransaction({\n address: hash,\n amount: cChainParams.current.proposalFee,\n isProposal: true,\n });\n if (ok) {\n proposal.txid = txid;\n const database = await Database.getInstance();\n\n // Fetch our Account, add the proposal to it\n const account = await database.getAccount();\n account.localProposals.push(proposal);\n\n // Update the DB\n await database.updateAccount(account);\n createAlert('success', translation.PROPOSAL_CREATED, 7500);\n updateGovernanceTab();\n }\n}\n\nexport function refreshChainData() {\n const cNet = getNetwork();\n // If in offline mode: don't sync ANY data or connect to the internet\n if (!cNet.enabled)\n return console.warn(\n 'Offline mode active: For your security, the wallet will avoid ALL internet requests.'\n );\n if (!masterKey) return;\n\n // Fetch block count + UTXOs, update the UI for new transactions\n cNet.getBlockCount().then((_) => {\n // Fetch latest Activity\n updateActivityGUI(false, true);\n\n // If it's open: update the Governance Dashboard\n if (doms.domGovTab.classList.contains('active')) {\n updateGovernanceTab();\n }\n });\n getBalance(true);\n}\n\n// A safety mechanism enabled if the user attempts to leave without encrypting/saving their keys\nexport const beforeUnloadListener = (evt) => {\n evt.preventDefault();\n // Disable Save your wallet warning on unload\n createAlert('warning', ALERTS.SAVE_WALLET_PLEASE, 10000);\n // Most browsers ignore this nowadays, but still, keep it 'just incase'\n return (evt.returnValue = translation.BACKUP_OR_ENCRYPT_WALLET);\n};\n\n/**\n * @typedef {Object} SettingsDOM - An object that contains the DOM elements for settings pages.\n * @property {HTMLElement} btn - The button to switch to this setting type.\n * @property {HTMLElement} section - The container for this setting type.\n */\n\n/**\n * Returns a list of all pages and their DOM elements.\n *\n * This must be a function, since, the DOM elements are `undefined` until\n * after the startup sequence.\n *\n * Types are inferred.\n */\nfunction getSettingsPages() {\n return {\n /** @type {SettingsDOM} */\n wallet: {\n btn: doms.domWalletSettingsBtn,\n section: doms.domWalletSettings,\n },\n /** @type {SettingsDOM} */\n display: {\n btn: doms.domDisplaySettingsBtn,\n section: doms.domDisplaySettings,\n },\n };\n}\n\n/**\n * Switch between screens in the settings menu\n * @param {string} page - The name of the setting page to switch to\n */\nexport function switchSettings(page) {\n const SETTINGS = getSettingsPages();\n const { btn, section } = SETTINGS[page];\n\n Object.values(SETTINGS).forEach(({ section, btn }) => {\n // Set the slider to the proper location\n if (page == 'display') {\n doms.domDisplayDecimalsSlider.oninput = function () {\n doms.domDisplayDecimalsSliderDisplay.innerHTML = this.value;\n //let val = ((((doms.domDisplayDecimalsSlider.offsetWidth - 24) / 9) ) * parseInt(this.value));\n\n //doms.domDisplayDecimalsSliderDisplay.style.marginLeft = (val) + 'px';\n };\n\n // Triggers the input event\n setTimeout(\n () =>\n doms.domDisplayDecimalsSlider.dispatchEvent(\n new Event('input')\n ),\n 10\n );\n }\n // Hide all settings sections\n section.classList.add('d-none');\n // Make all buttons inactive\n btn.classList.remove('active');\n });\n\n // Show selected section and make its button active\n section.classList.remove('d-none');\n btn.classList.add('active');\n}\n\nfunction errorHandler(e) {\n const message = `${translation.unhandledException}
${sanitizeHTML(\n e.message || e.reason\n )}`;\n try {\n createAlert('warning', message);\n } catch (_) {\n // Something as gone wrong, so we fall back to the default alert\n // This can happen on early errors for example\n alert(message);\n }\n}\n\n// This code is ran in the vanity gen worker as well!\n// In which case, window would be not defined.\n// `if (window)` wouldn't work either because\n// window is not defined as opposed to undefined\ntry {\n window.addEventListener('error', errorHandler);\n window.addEventListener('unhandledrejection', errorHandler);\n} catch (_) {}\n","import { getDerivationPath } from './wallet.js';\nimport { cChainParams, COIN } from './chain_params.js';\nimport { createAlert } from './misc.js';\nimport { Mempool, UTXO } from './mempool.js';\nimport { getEventEmitter } from './event_bus.js';\nimport {\n STATS,\n cStatKeys,\n cAnalyticsLevel,\n setExplorer,\n fAutoSwitch,\n} from './settings.js';\nimport { ALERTS } from './i18n.js';\n\n/**\n * @typedef {Object} XPUBAddress\n * @property {string} type - Type of address (always 'XPUBAddress' for XPUBInfo classes)\n * @property {string} name - PIVX address string\n * @property {string} path - BIP44 path of the address derivation\n * @property {number} transfers - Number of transfers involving the address\n * @property {number} decimals - Decimal places in the amounts (PIVX has 8 decimals)\n * @property {string} balance - Current balance of the address (satoshi)\n * @property {string} totalReceived - Total ever received by the address (satoshi)\n * @property {string} totalSent - Total ever sent from the address (satoshi)\n */\n\n/**\n * @typedef {Object} XPUBInfo\n * @property {number} page - Current response page in a paginated data\n * @property {number} totalPages - Total pages in the paginated data\n * @property {number} itemsOnPage - Number of items on the current page\n * @property {string} address - XPUB string of the address\n * @property {string} balance - Current balance of the xpub (satoshi)\n * @property {string} totalReceived - Total ever received by the xpub (satoshi)\n * @property {string} totalSent - Total ever sent from the xpub (satoshi)\n * @property {string} unconfirmedBalance - Unconfirmed balance of the xpub (satoshi)\n * @property {number} unconfirmedTxs - Number of unconfirmed transactions of the xpub\n * @property {number} txs - Total number of transactions of the xpub\n * @property {string[]?} txids - Transaction ids involving the xpub\n * @property {number?} usedTokens - Number of used token addresses from the xpub\n * @property {XPUBAddress[]?} tokens - Array of used token addresses\n */\n\n/**\n * A historical transaction type.\n * @enum {number}\n */\nexport const HistoricalTxType = {\n UNKNOWN: 0,\n STAKE: 1,\n DELEGATION: 2,\n UNDELEGATION: 3,\n RECEIVED: 4,\n SENT: 5,\n};\n\n/**\n * A historical transaction\n */\nexport class HistoricalTx {\n /**\n * @param {HistoricalTxType} type - The type of transaction.\n * @param {string} id - The transaction ID.\n * @param {Array} senders - The list of 'input addresses'.\n * @param {Array} receivers - The list of 'output addresses'.\n * @param {boolean} shieldedOutputs - If this transaction contains Shield outputs.\n * @param {number} time - The block time of the transaction.\n * @param {number} blockHeight - The block height of the transaction.\n * @param {number} amount - The amount transacted, in coins.\n */\n constructor(\n type,\n id,\n senders,\n receivers,\n shieldedOutputs,\n time,\n blockHeight,\n amount\n ) {\n this.type = type;\n this.id = id;\n this.senders = senders;\n this.receivers = receivers;\n this.shieldedOutputs = shieldedOutputs;\n this.time = time;\n this.blockHeight = blockHeight;\n this.amount = amount;\n }\n}\n\n/**\n * Virtual class rapresenting any network backend\n */\nexport class Network {\n constructor(masterKey) {\n if (this.constructor === Network) {\n throw new Error('Initializing virtual class');\n }\n this._enabled = true;\n\n this.masterKey = masterKey;\n\n this.lastWallet = 0;\n this.isHistorySynced = false;\n }\n\n /**\n * @param {boolean} value\n */\n set enabled(value) {\n if (value !== this._enabled) {\n getEventEmitter().emit('network-toggle', value);\n this._enabled = value;\n }\n }\n\n get enabled() {\n return this._enabled;\n }\n\n enable() {\n this.enabled = true;\n }\n\n disable() {\n this.enabled = false;\n }\n\n toggle() {\n this.enabled = !this.enabled;\n }\n\n getFee(bytes) {\n // TEMPORARY: Hardcoded fee per-byte\n return bytes * 50; // 50 sat/byte\n }\n\n get cachedBlockCount() {\n throw new Error('cachedBlockCount must be implemented');\n }\n\n error() {\n throw new Error('Error must be implemented');\n }\n\n getBlockCount() {\n throw new Error('getBlockCount must be implemented');\n }\n\n sentTransaction() {\n throw new Error('sendTransaction must be implemented');\n }\n\n submitAnalytics(_strType, _cData = {}) {\n throw new Error('submitAnalytics must be implemented');\n }\n\n setMasterKey(masterKey) {\n this.masterKey = masterKey;\n }\n\n async getTxInfo(_txHash) {\n throw new Error('getTxInfo must be implemented');\n }\n}\n\n/**\n *\n */\nexport class ExplorerNetwork extends Network {\n /**\n * @param {string} strUrl - Url pointing to the blockbook explorer\n */\n constructor(strUrl, masterKey) {\n super(masterKey);\n /**\n * @type{string}\n * @public\n */\n this.strUrl = strUrl;\n\n /**\n * @type{Number}\n * @private\n */\n this.blocks = 0;\n\n /**\n * @type {Array}\n */\n this.arrTxHistory = [];\n\n this.historySyncing = false;\n }\n\n error() {\n if (this.enabled) {\n this.disable();\n createAlert('warning', ALERTS.CONNECTION_FAILED);\n }\n }\n\n get cachedBlockCount() {\n return this.blocks;\n }\n\n async getBlockCount() {\n try {\n getEventEmitter().emit('sync-status', 'start');\n const { backend } = await (\n await retryWrapper(fetchBlockbook, `/api/v2/api`)\n ).json();\n if (backend.blocks > this.blocks) {\n console.log(\n 'New block detected! ' +\n this.blocks +\n ' --> ' +\n backend.blocks\n );\n this.blocks = backend.blocks;\n\n await this.getUTXOs();\n }\n } catch (e) {\n this.error();\n throw e;\n } finally {\n getEventEmitter().emit('sync-status', 'stop');\n }\n }\n\n /**\n * @typedef {object} BlockbookUTXO\n * @property {string} txid - The TX hash of the output\n * @property {number} vout - The Index Position of the output\n * @property {string} value - The string-based satoshi value of the output\n * @property {number} height - The block height the TX was confirmed in\n * @property {number} confirmations - The depth of the TX in the blockchain\n */\n\n /**\n * Fetch UTXOs from the current primary explorer\n * @param {string} strAddress - Optional address, gets UTXOs without changing MPW's state\n * @returns {Promise>} Resolves when it has finished fetching UTXOs\n */\n async getUTXOs(strAddress = '') {\n // Don't fetch UTXOs if we're already scanning for them!\n if (!strAddress) {\n if (!this.masterKey) return;\n if (this.isSyncing) return;\n this.isSyncing = true;\n }\n try {\n let publicKey;\n // Derive our XPub, or fetch a single pubkey\n if (this.masterKey.isHD && !strAddress) {\n const derivationPath = getDerivationPath(\n this.masterKey.isHardwareWallet\n )\n .split('/')\n .slice(0, 4)\n .join('/');\n publicKey = await this.masterKey.getxpub(derivationPath);\n } else {\n // Use the param address if specified, or the Master Key by default\n publicKey = strAddress || (await this.masterKey.getAddress());\n }\n\n // Fetch UTXOs for the key\n const arrUTXOs = await (\n await retryWrapper(fetchBlockbook, `/api/v2/utxo/${publicKey}`)\n ).json();\n\n // If using MPW's wallet, then sync the UTXOs in MPW's state\n if (!strAddress) getEventEmitter().emit('utxo', arrUTXOs);\n\n // Return the UTXOs for additional utility use\n return arrUTXOs;\n } catch (e) {\n console.error(e);\n this.error();\n } finally {\n this.isSyncing = false;\n }\n }\n /**\n * Fetches UTXOs full info\n * @param {Object} cUTXO - object-formatted UTXO\n * @returns {Promise} Promise that resolves with the full info of the UTXO\n */\n async getUTXOFullInfo(cUTXO) {\n const cTx = await (\n await retryWrapper(\n fetchBlockbook,\n `/api/v2/tx-specific/${cUTXO.txid}`\n )\n ).json();\n const cVout = cTx.vout[cUTXO.vout];\n\n let path;\n if (cUTXO.path) {\n path = cUTXO.path.split('/');\n path[2] =\n (this.masterKey.isHardwareWallet\n ? cChainParams.current.BIP44_TYPE_LEDGER\n : cChainParams.current.BIP44_TYPE) + \"'\";\n this.lastWallet = Math.max(parseInt(path[5]), this.lastWallet);\n path = path.join('/');\n }\n\n const isColdStake = cVout.scriptPubKey.type === 'coldstake';\n const isStandard = cVout.scriptPubKey.type === 'pubkeyhash';\n const isReward = cTx.vout[0].scriptPubKey.hex === '';\n // We don't know what this is\n if (!isColdStake && !isStandard) {\n return null;\n }\n\n return new UTXO({\n id: cUTXO.txid,\n path,\n sats: Math.round(cVout.value * COIN),\n script: cVout.scriptPubKey.hex,\n vin: cTx?.vin || [],\n vout: cVout.n,\n height: this.cachedBlockCount - (cTx.confirmations - 1),\n status: cTx.confirmations < 1 ? Mempool.PENDING : Mempool.CONFIRMED,\n isDelegate: isColdStake,\n isReward,\n });\n }\n\n /**\n * Fetch an XPub's basic information\n * @param {string} strXPUB - The xpub to fetch info for\n * @returns {Promise} - A JSON class of aggregated XPUB info\n */\n async getXPubInfo(strXPUB) {\n return await (\n await retryWrapper(fetchBlockbook, `/api/v2/xpub/${strXPUB}`)\n ).json();\n }\n\n async sendTransaction(hex) {\n try {\n const data = await (\n await retryWrapper(fetchBlockbook, '/api/v2/sendtx/', {\n method: 'post',\n body: hex,\n })\n ).json();\n\n // Throw and catch if the data is not a TXID\n if (!data.result || data.result.length !== 64) throw data;\n\n console.log('Transaction sent! ' + data.result);\n getEventEmitter().emit('transaction-sent', true, data.result);\n return data.result;\n } catch (e) {\n getEventEmitter().emit('transaction-sent', false, e);\n return false;\n }\n }\n\n /**\n * Synchronise a partial chunk of our TX history\n * @param {boolean} [fNewOnly] - Whether to sync ONLY new transactions\n */\n async syncTxHistoryChunk(fNewOnly = false) {\n // Do not allow multiple calls at once\n if (this.historySyncing) {\n return false;\n }\n try {\n if (!this.enabled || !this.masterKey) return this.arrTxHistory;\n this.historySyncing = true;\n const nHeight = this.arrTxHistory.length\n ? this.arrTxHistory[this.arrTxHistory.length - 1].blockHeight\n : 0;\n const mapPaths = new Map();\n\n // Form the API call using our wallet information\n const fHD = this.masterKey.isHD;\n const strDerivPath = getDerivationPath(\n this.masterKey.isHardwareWallet\n )\n .split('/')\n .slice(0, 4)\n .join('/');\n const strKey = fHD\n ? await this.masterKey.getxpub(strDerivPath)\n : await this.masterKey.getAddress();\n const strRoot = `/api/v2/${fHD ? 'xpub/' : 'address/'}${strKey}`;\n const strCoreParams = `?details=txs&tokens=derived&pageSize=200`;\n const strAPI = strRoot + strCoreParams;\n\n // If we have a known block height, check for incoming transactions within the last 60 blocks\n const cRecentTXs =\n this.blocks > 0\n ? await (\n await retryWrapper(\n fetchBlockbook,\n `${strAPI}&from=${this.blocks - 60}`\n )\n ).json()\n : {};\n\n // If we do not have full history, then load more historical TXs in a slice\n const cData =\n !fNewOnly && !this.isHistorySynced\n ? await (\n await retryWrapper(\n fetchBlockbook,\n `${strAPI}&to=${nHeight ? nHeight - 1 : 0}`\n )\n ).json()\n : {};\n if (fHD && (cData.tokens || cRecentTXs.tokens)) {\n // Map all address <--> derivation paths\n // - From historical transactions\n if (cData.tokens) {\n cData.tokens.forEach((cAddrPath) =>\n mapPaths.set(cAddrPath.name, cAddrPath.path)\n );\n }\n // - From new transactions\n if (cRecentTXs.tokens) {\n cRecentTXs.tokens.forEach((cAddrPath) =>\n mapPaths.set(cAddrPath.name, cAddrPath.path)\n );\n }\n } else {\n mapPaths.set(strKey, ':)');\n }\n\n // Process our aggregated history data\n if (\n (cData && cData.transactions) ||\n (cRecentTXs && cRecentTXs.transactions)\n ) {\n // Process Older (historical) TXs\n const arrOlderTXs = this.toHistoricalTXs(\n cData.transactions || [],\n mapPaths\n );\n\n // Process Recent TXs, then add them manually on the basis that they are NOT already known in history\n const arrRecentTXs = this.toHistoricalTXs(\n cRecentTXs.transactions || [],\n mapPaths\n );\n for (const cTx of arrRecentTXs) {\n if (\n !this.arrTxHistory.find((a) => a.id === cTx.id) &&\n !arrOlderTXs.find((a) => a.id === cTx.id)\n ) {\n // No identical Tx, so prepend it!\n this.arrTxHistory.unshift(cTx);\n }\n }\n this.arrTxHistory = this.arrTxHistory.concat(arrOlderTXs);\n\n // If the results don't match the full 'max/requested results', then we know the history is complete\n if (\n cData.transactions &&\n cData.transactions.length !== cData.itemsOnPage\n ) {\n this.isHistorySynced = true;\n }\n }\n return this.arrTxHistory;\n } catch (e) {\n console.error(e);\n } finally {\n this.historySyncing = false;\n }\n }\n\n /**\n * Convert a list of Blockbook transactions to HistoricalTxs\n * @param {Array} arrTXs - An array of the Blockbook TXs\n * @param {Map} mapPaths - A map of the derivation paths for involved addresses\n * @returns {Array} - A new array of `HistoricalTx`-formatted transactions\n */\n toHistoricalTXs(arrTXs, mapPaths) {\n /**\n * A function to sum a list of inputs (vin) or outputs (vout)\n * @type {(v: Array<{addresses: String[], value: Number}>) => Number}\n */\n const txSum = (v) =>\n v.reduce(\n (t, s) =>\n t +\n (s.addresses &&\n s.addresses.some((strAddr) => mapPaths.has(strAddr))\n ? parseInt(s.value)\n : 0),\n 0\n );\n\n return arrTXs\n .map((tx) => {\n // The total 'delta' or change in balance, from the Tx's sums\n let nAmount = (txSum(tx.vout) - txSum(tx.vin)) / COIN;\n\n // If this Tx creates any Shield outputs\n // Note: shielOuts typo intended, this is a Blockbook error\n const fShieldOuts = Number.isFinite(tx.shielOuts);\n\n // (Un)Delegated coins in this transaction, if any\n let nDelegated = 0;\n\n // The address(es) delegated to, if any\n let strDelegatedAddr = '';\n\n // The sender addresses, if any\n const arrSenders =\n tx.vin?.flatMap((vin) => vin.addresses) || [];\n\n // The receiver addresses, if any\n let arrReceivers =\n tx.vout?.flatMap((vout) => vout.addresses) || [];\n // Pretty-fy script addresses\n arrReceivers = arrReceivers.map((addr) =>\n addr.startsWith('OP_') ? 'Contract' : addr\n );\n\n // Figure out the type, based on the Tx's properties\n let type = HistoricalTxType.UNKNOWN;\n if (\n !fShieldOuts &&\n tx?.vout[0]?.addresses[0]?.startsWith('CoinStake')\n ) {\n type = HistoricalTxType.STAKE;\n } else if (nAmount > 0 || (nAmount > 0 && fShieldOuts)) {\n type = HistoricalTxType.RECEIVED;\n // If this contains Shield outputs, then we received them\n if (fShieldOuts)\n nAmount = parseInt(tx.valueBalanceSat) / COIN;\n } else if (nAmount < 0 || (nAmount < 0 && fShieldOuts)) {\n // Check vins for undelegations\n for (const vin of tx.vin) {\n const fDelegation = vin.addresses?.some((addr) =>\n addr.startsWith(cChainParams.current.STAKING_PREFIX)\n );\n if (fDelegation) {\n nDelegated -= parseInt(vin.value);\n }\n }\n\n // Check vouts for delegations\n for (const out of tx.vout) {\n strDelegatedAddr =\n out.addresses?.find((addr) =>\n addr.startsWith(\n cChainParams.current.STAKING_PREFIX\n )\n ) || strDelegatedAddr;\n\n const fDelegation = !!strDelegatedAddr;\n if (fDelegation) {\n nDelegated += parseInt(out.value);\n }\n }\n\n // If a delegation was made, then display the value delegated\n if (nDelegated > 0) {\n type = HistoricalTxType.DELEGATION;\n nAmount = nDelegated / COIN;\n } else if (nDelegated < 0) {\n type = HistoricalTxType.UNDELEGATION;\n nAmount = nDelegated / COIN;\n } else {\n type = HistoricalTxType.SENT;\n // If this contains Shield outputs, then we sent them\n if (fShieldOuts)\n nAmount = parseInt(tx.valueBalanceSat) / COIN;\n }\n }\n\n return new HistoricalTx(\n type,\n tx.txid,\n arrSenders,\n nDelegated !== 0 ? [strDelegatedAddr] : arrReceivers,\n fShieldOuts,\n tx.blockTime,\n tx.blockHeight,\n Math.abs(nAmount)\n );\n })\n .filter((tx) => tx.amount != 0);\n }\n\n async setMasterKey(masterKey) {\n // If the public Master Key (xpub, address...) is different, then wipe TX history\n if (\n (await this.masterKey?.keyToExport) !==\n (await masterKey?.keyToExport)\n ) {\n this.arrTxHistory = [];\n }\n\n // Set the key\n this.masterKey = masterKey;\n }\n\n async getTxInfo(txHash) {\n const req = await retryWrapper(fetchBlockbook, `/api/v2/tx/${txHash}`);\n return await req.json();\n }\n\n // PIVX Labs Analytics: if you are a user, you can disable this FULLY via the Settings.\n // ... if you're a developer, we ask you to keep these stats to enhance upstream development,\n // ... but you are free to completely strip MPW of any analytics, if you wish, no hard feelings.\n submitAnalytics(strType, cData = {}) {\n if (!this.enabled) return;\n\n // TODO: rebuild Labs Analytics, submitAnalytics() will be disabled at code-level until this is live again\n /* eslint-disable */\n return;\n\n // Limit analytics here to prevent 'leakage' even if stats are implemented incorrectly or forced\n let i = 0,\n arrAllowedKeys = [];\n for (i; i < cAnalyticsLevel.stats.length; i++) {\n const cStat = cAnalyticsLevel.stats[i];\n arrAllowedKeys.push(cStatKeys.find((a) => STATS[a] === cStat));\n }\n\n // Check if this 'stat type' was granted permissions\n if (!arrAllowedKeys.includes(strType)) return false;\n\n // Format\n const cStats = { type: strType, ...cData };\n\n // Send to Labs Analytics\n const request = new XMLHttpRequest();\n request.open('POST', 'https://scpscan.net/mpw/statistic', true);\n request.setRequestHeader('Content-Type', 'application/json');\n request.send(JSON.stringify(cStats));\n return true;\n }\n}\n\nlet _network = null;\n\n/**\n * Sets the network in use by MPW.\n * @param {ExplorerNetwork} network - network to use\n */\nexport function setNetwork(network) {\n _network = network;\n}\n\n/**\n * Gets the network in use by MPW.\n * @returns {ExplorerNetwork?} Returns the network in use, may be null if MPW hasn't properly loaded yet.\n */\nexport function getNetwork() {\n return _network;\n}\n\n/**\n * A Fetch wrapper which uses the current Blockbook Network's base URL\n * @param {string} api - The specific Blockbook api to call\n * @param {RequestInit} options - The Fetch options\n * @returns {Promise} - The unresolved Fetch promise\n */\nexport function fetchBlockbook(api, options) {\n return fetch(_network.strUrl + api, options);\n}\n\n/**\n * A wrapper for Blockbook calls which can, in the event of an unresponsive explorer,\n * seamlessly attempt the same call on multiple other explorers until success.\n * @param {Function} func - The function to re-attempt with\n * @param {...any} args - The arguments to pass to the function\n */\nasync function retryWrapper(func, ...args) {\n // Track internal errors from the wrapper\n let err;\n\n // If allowed by the user, Max Tries is ALL MPW-supported explorers, otherwise, restrict to only the current one.\n let nMaxTries = cChainParams.current.Explorers.length;\n let retries = 0;\n\n // The explorer index we started at\n let nIndex = cChainParams.current.Explorers.findIndex(\n (a) => a.url === getNetwork().strUrl\n );\n\n // Run the call until successful, or all attempts exhausted\n while (retries < nMaxTries) {\n try {\n // Call the passed function with the arguments\n const res = await func(...args);\n\n // If the endpoint is non-OK, assume it's an error\n if (!res.ok) throw res;\n\n // Return the result if successful\n return res;\n } catch (error) {\n err = error;\n\n // If allowed, switch explorers\n if (!fAutoSwitch) throw err;\n nIndex = (nIndex + 1) % cChainParams.current.Explorers.length;\n const cNewExplorer = cChainParams.current.Explorers[nIndex];\n\n // Set the explorer at Network-class level, then as a hacky workaround for the current callback; we\n // ... adjust the internal URL to the new explorer.\n getNetwork().strUrl = cNewExplorer.url;\n setExplorer(cNewExplorer, true);\n\n // Bump the attempts, and re-try next loop\n retries++;\n }\n }\n\n // Throw an error so the calling code knows the operation failed\n throw err;\n}\n","const buff_to_base64 = (buff) => btoa(String.fromCharCode.apply(null, buff));\n\nconst base64_to_buf = (b64) =>\n Uint8Array.from(atob(b64), (c) => c.charCodeAt(null));\n\nconst enc = new TextEncoder();\nconst dec = new TextDecoder();\n\nexport async function encrypt(data, strPassword = '') {\n const strPass =\n strPassword ||\n window.prompt('Please enter your wallet encryption password');\n if (!strPass) return false;\n return await encryptData(data, strPass);\n}\n\nexport async function decrypt(data, strPassword) {\n const strPass =\n strPassword ||\n window.prompt('Please enter your wallet unlock password');\n if (!strPass) return false;\n return (await decryptData(data, strPass)) || 'decryption failed!';\n}\n\nconst getPasswordKey = (password) =>\n window.crypto.subtle.importKey(\n 'raw',\n enc.encode(password),\n 'PBKDF2',\n false,\n ['deriveKey']\n );\n\nconst deriveKey = (passwordKey, salt, keyUsage) =>\n window.crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt,\n iterations: 250000,\n hash: 'SHA-256',\n },\n passwordKey,\n { name: 'AES-GCM', length: 256 },\n false,\n keyUsage\n );\n\nasync function encryptData(secretData, password) {\n try {\n const salt = window.crypto.getRandomValues(new Uint8Array(16));\n const iv = window.crypto.getRandomValues(new Uint8Array(12));\n const passwordKey = await getPasswordKey(password);\n const aesKey = await deriveKey(passwordKey, salt, ['encrypt']);\n const encryptedContent = await window.crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv: iv,\n },\n aesKey,\n enc.encode(secretData)\n );\n\n const encryptedContentArr = new Uint8Array(encryptedContent);\n let buff = new Uint8Array(\n salt.byteLength + iv.byteLength + encryptedContentArr.byteLength\n );\n buff.set(salt, 0);\n buff.set(iv, salt.byteLength);\n buff.set(encryptedContentArr, salt.byteLength + iv.byteLength);\n return buff_to_base64(buff);\n } catch (e) {\n console.log(`Error - ${e}`);\n return '';\n }\n}\n\nasync function decryptData(encryptedData, password) {\n try {\n const encryptedDataBuff = base64_to_buf(encryptedData);\n const salt = encryptedDataBuff.slice(0, 16);\n const iv = encryptedDataBuff.slice(16, 16 + 12);\n const data = encryptedDataBuff.slice(16 + 12);\n const passwordKey = await getPasswordKey(password);\n const aesKey = await deriveKey(passwordKey, salt, ['decrypt']);\n const decryptedContent = await window.crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: iv,\n },\n aesKey,\n data\n );\n return dec.decode(decryptedContent);\n } catch (e) {\n console.log(`Error - ${e}`);\n return '';\n }\n}\n","import { hexToBytes, bytesToHex, dSHA256 } from './utils.js';\nimport * as nobleSecp256k1 from '@noble/secp256k1';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { ripemd160 } from '@noble/hashes/ripemd160';\nimport { generateMnemonic, mnemonicToSeed, validateMnemonic } from 'bip39';\nimport { doms, beforeUnloadListener } from './global.js';\nimport HDKey from 'hdkey';\nimport { getNetwork } from './network.js';\nimport {\n pubKeyHashNetworkLen,\n confirmPopup,\n writeToUint8,\n pubPrebaseLen,\n createAlert,\n sleep,\n getSafeRand,\n isXPub,\n isStandardAddress,\n} from './misc.js';\nimport {\n refreshChainData,\n setDisplayForAllWalletOptions,\n getBalance,\n getStakingBalance,\n} from './global.js';\nimport {\n cChainParams,\n MAX_ACCOUNT_GAP,\n PRIVKEY_BYTE_LENGTH,\n} from './chain_params.js';\nimport { ALERTS, tr, translation } from './i18n.js';\nimport { encrypt, decrypt } from './aes-gcm.js';\nimport bs58 from 'bs58';\nimport AppBtc from '@ledgerhq/hw-app-btc';\nimport TransportWebUSB from '@ledgerhq/hw-transport-webusb';\nimport createXpub from 'create-xpub';\nimport * as jdenticon from 'jdenticon';\nimport { Database } from './database.js';\nimport { guiRenderCurrentReceiveModal } from './contacts-book.js';\nimport { Account } from './accounts.js';\n\nexport let fWalletLoaded = false;\n\n/**\n * Abstract class masterkey\n * @abstract\n */\nclass MasterKey {\n #addressIndex = 0;\n /**\n * Map our own address -> Path\n * @type {Map}\n */\n #ownAddresses = new Map();\n\n constructor() {\n if (this.constructor === MasterKey) {\n throw new Error('initializing virtual class');\n }\n }\n\n /**\n * @param {String} [path] - BIP32 path pointing to the private key.\n * @return {Promise>} Array of bytes containing private key\n * @abstract\n */\n async getPrivateKeyBytes(_path) {\n throw new Error('Not implemented');\n }\n\n /**\n * @param {String} [path] - BIP32 path pointing to the private key.\n * @return {Promise} encoded private key\n * @abstract\n */\n async getPrivateKey(path) {\n return generateOrEncodePrivkey(await this.getPrivateKeyBytes(path))\n .strWIF;\n }\n\n /**\n * @param {String} [path] - BIP32 path pointing to the address\n * @return {Promise} Address\n * @abstract\n */\n async getAddress(path) {\n return deriveAddress({ pkBytes: await this.getPrivateKeyBytes(path) });\n }\n\n /**\n * @param {String} path - BIP32 path pointing to the xpub\n * @return {Promise} xpub\n * @abstract\n */\n async getxpub(_path) {\n throw new Error('Not implemented');\n }\n\n /**\n * Wipe all private data from key.\n * @return {void}\n * @abstract\n */\n wipePrivateData() {\n throw new Error('Not implemented');\n }\n\n /**\n * @return {String} private key suitable for backup.\n * @abstract\n */\n get keyToBackup() {\n throw new Error('Not implemented');\n }\n\n /**\n * @return {Promise} public key to export. Only suitable for monitoring balance.\n * @abstract\n */\n get keyToExport() {\n throw new Error('Not implemented');\n }\n\n /**\n * @return {Boolean} Whether or not this is a Hierarchical Deterministic wallet\n */\n get isHD() {\n return this._isHD;\n }\n\n /**\n * @return {Boolean} Whether or not this is a hardware wallet\n */\n get isHardwareWallet() {\n return this._isHardwareWallet;\n }\n\n /**\n * @return {Boolean} Whether or not this key is view only or not\n */\n get isViewOnly() {\n return this._isViewOnly;\n }\n\n /**\n * @param {string} address - address to check\n * @return {Promise} BIP32 path or null if it's not your address\n */\n async isOwnAddress(address) {\n if (this.#ownAddresses.has(address)) {\n return this.#ownAddresses.get(address);\n }\n const last = getNetwork().lastWallet;\n this.#addressIndex =\n this.#addressIndex > last ? this.#addressIndex : last;\n if (this.isHD) {\n for (let i = 0; i < this.#addressIndex; i++) {\n const path = getDerivationPath(this.isHardwareWallet, 0, 0, i);\n const testAddress = await masterKey.getAddress(path);\n if (address === testAddress) {\n this.#ownAddresses.set(address, path);\n return path;\n }\n }\n } else {\n const value = address === (await this.keyToExport) ? ':)' : null;\n this.#ownAddresses.set(address, value);\n return value;\n }\n\n this.#ownAddresses.set(address, null);\n return null;\n }\n\n /**\n * @return Promise<[string, string]> Address and its BIP32 derivation path\n */\n async getNewAddress() {\n const last = getNetwork().lastWallet;\n this.#addressIndex =\n (this.#addressIndex > last ? this.#addressIndex : last) + 1;\n if (this.#addressIndex - last > MAX_ACCOUNT_GAP) {\n // If the user creates more than ${MAX_ACCOUNT_GAP} empty wallets we will not be able to sync them!\n this.#addressIndex = last;\n }\n const path = getDerivationPath(\n this.isHardwareWallet,\n 0,\n 0,\n this.#addressIndex\n );\n const address = await this.getAddress(path);\n return [address, path];\n }\n\n /**\n * Derive the current address (by internal index)\n * @return {Promise} Address\n * @abstract\n */\n async getCurrentAddress() {\n return await this.getAddress(\n getDerivationPath(this.isHardwareWallet, 0, 0, this.#addressIndex)\n );\n }\n}\n\nexport class HdMasterKey extends MasterKey {\n constructor({ seed, xpriv, xpub }) {\n super();\n // Generate the HDKey\n if (seed) this._hdKey = HDKey.fromMasterSeed(seed);\n if (xpriv) this._hdKey = HDKey.fromExtendedKey(xpriv);\n if (xpub) this._hdKey = HDKey.fromExtendedKey(xpub);\n this._isViewOnly = !!xpub;\n if (!this._hdKey)\n throw new Error('All of seed, xpriv and xpub are undefined');\n this._isHD = true;\n this._isHardwareWallet = false;\n }\n\n async getPrivateKeyBytes(path) {\n if (this.isViewOnly) {\n throw new Error(\n 'Trying to get private key bytes from a view only key'\n );\n }\n return this._hdKey.derive(path).privateKey;\n }\n\n get keyToBackup() {\n if (this.isViewOnly) {\n throw new Error('Trying to get private key from a view only key');\n }\n return this._hdKey.privateExtendedKey;\n }\n\n async getxpub(path) {\n if (this.isViewOnly) return this._hdKey.publicExtendedKey;\n return this._hdKey.derive(path).publicExtendedKey;\n }\n\n getAddress(path) {\n let child;\n if (this.isViewOnly) {\n // If we're view only we can't derive hardened keys, so we'll assume\n // That the xpub has already been derived\n child = this._hdKey.derive(\n path\n .split('/')\n .filter((n) => !n.includes(\"'\"))\n .join('/')\n );\n } else {\n child = this._hdKey.derive(path);\n }\n return deriveAddress({ publicKey: bytesToHex(child.publicKey) });\n }\n\n wipePrivateData() {\n if (this._isViewOnly) return;\n\n this._hdKey = HDKey.fromExtendedKey(this.keyToExport);\n this._isViewOnly = true;\n }\n\n get keyToExport() {\n if (this._isViewOnly) return this._hdKey.publicExtendedKey;\n // We need the xpub to point at the account level\n return this._hdKey.derive(\n getDerivationPath(false, 0, 0, 0, false)\n .split('/')\n .slice(0, 4)\n .join('/')\n ).publicExtendedKey;\n }\n}\n\nexport class HardwareWalletMasterKey extends MasterKey {\n constructor() {\n super();\n this._isHD = true;\n this._isHardwareWallet = true;\n }\n async getPrivateKeyBytes(_path) {\n throw new Error('Hardware wallets cannot export private keys');\n }\n\n async getAddress(path, { verify } = {}) {\n return deriveAddress({\n publicKey: await this.getPublicKey(path, { verify }),\n });\n }\n\n async getPublicKey(path, { verify } = {}) {\n return deriveAddress({\n publicKey: await getHardwareWalletKeys(path, false, verify),\n output: 'COMPRESSED_HEX',\n });\n }\n\n get keyToBackup() {\n throw new Error(\"Hardware wallets don't have keys to backup\");\n }\n\n async getxpub(path) {\n if (!this.xpub) {\n this.xpub = await getHardwareWalletKeys(path, true);\n }\n return this.xpub;\n }\n\n // Hardware Wallets don't have exposed private data\n wipePrivateData() {}\n\n get isViewOnly() {\n return false;\n }\n get keyToExport() {\n const derivationPath = getDerivationPath(masterKey.isHardwareWallet)\n .split('/')\n .slice(0, 4)\n .join('/');\n return this.getxpub(derivationPath);\n }\n}\n\nexport class LegacyMasterKey extends MasterKey {\n constructor({ pkBytes, address }) {\n super();\n this._isHD = false;\n this._isHardwareWallet = false;\n this._pkBytes = pkBytes;\n this._address = address || super.getAddress();\n this._isViewOnly = !!address;\n }\n\n getAddress() {\n return this._address;\n }\n\n get keyToExport() {\n return this._address;\n }\n\n async getPrivateKeyBytes(_path) {\n if (this.isViewOnly) {\n throw new Error(\n 'Trying to get private key bytes from a view only key'\n );\n }\n return this._pkBytes;\n }\n\n get keyToBackup() {\n return generateOrEncodePrivkey(this._pkBytes).strWIF;\n }\n\n async getxpub(_path) {\n throw new Error(\n 'Trying to get an extended public key from a legacy address'\n );\n }\n\n wipePrivateData() {\n this._pkBytes = null;\n this._isViewOnly = true;\n }\n}\n\n// Ledger Hardware wallet constants\nexport const LEDGER_ERRS = new Map([\n // Ledger error code <--> User-friendly string\n [25870, 'Open the PIVX app on your device'],\n [25873, 'Open the PIVX app on your device'],\n [57408, 'Navigate to the PIVX app on your device'],\n [27157, 'Wrong app! Open the PIVX app on your device'],\n [27266, 'Wrong app! Open the PIVX app on your device'],\n [27904, 'Wrong app! Open the PIVX app on your device'],\n [27010, 'Unlock your Ledger, then try again!'],\n [27404, 'Unlock your Ledger, then try again!'],\n]);\n\n/**\n * @type{MasterKey}\n */\nexport let masterKey;\n\n// Construct a full BIP44 pubkey derivation path from it's parts\nexport function getDerivationPath(\n fLedger = false,\n nAccount = 0,\n nReceiving = 0,\n nIndex = 0,\n /**\n * When `true` will derive based on local wallet properties, when `false` it\n * will default to only accept given params and ignore the local configuration\n * @type {boolean}\n */\n fLocalWallet = true\n) {\n // Coin-Type is different on Ledger, as such, for local wallets; we modify it if we're using a Ledger to derive a key\n const strCoinType =\n fLocalWallet && fLedger\n ? cChainParams.current.BIP44_TYPE_LEDGER\n : cChainParams.current.BIP44_TYPE;\n if (fLocalWallet && masterKey && !masterKey.isHD && !fLedger) {\n return `:)//${strCoinType}'`;\n }\n return `m/44'/${strCoinType}'/${nAccount}'/${nReceiving}/${nIndex}`;\n}\n\n// Verify the integrity of a WIF private key, optionally parsing and returning the key payload\nexport function verifyWIF(\n strWIF = '',\n fParseBytes = false,\n skipVerification = false\n) {\n // Convert from Base58\n const bWIF = bs58.decode(strWIF);\n\n if (!skipVerification) {\n // Verify the byte length\n if (bWIF.byteLength !== PRIVKEY_BYTE_LENGTH) {\n throw Error(\n 'Private key length (' +\n bWIF.byteLength +\n ') is invalid, should be ' +\n PRIVKEY_BYTE_LENGTH +\n '!'\n );\n }\n\n // Verify the network byte\n if (bWIF[0] !== cChainParams.current.SECRET_KEY) {\n // Find the network it's trying to use, if any\n const cNetwork = Object.keys(cChainParams)\n .filter((strNet) => strNet !== 'current')\n .map((strNet) => cChainParams[strNet])\n .find((cNet) => cNet.SECRET_KEY === bWIF[0]);\n // Give a specific alert based on the byte properties\n throw Error(\n cNetwork\n ? 'This private key is for ' +\n (cNetwork.isTestnet ? 'Testnet' : 'Mainnet') +\n ', wrong network!'\n : 'This private key belongs to another coin, or is corrupted.'\n );\n }\n\n // Perform SHA256d hash of the WIF bytes\n const shaHash = dSHA256(bWIF.slice(0, 34));\n\n // Verify checksum (comparison by String since JS hates comparing object-like primitives)\n const bChecksumWIF = bWIF.slice(bWIF.byteLength - 4);\n const bChecksum = shaHash.slice(0, 4);\n if (bChecksumWIF.join('') !== bChecksum.join('')) {\n throw Error(\n 'Private key checksum is invalid, key may be modified, mis-typed, or corrupt.'\n );\n }\n }\n\n return fParseBytes ? Uint8Array.from(bWIF.slice(1, 33)) : true;\n}\n\n// A convenient alias to verifyWIF that returns the raw byte payload\nexport function parseWIF(strWIF, skipVerification = false) {\n return verifyWIF(strWIF, true, skipVerification);\n}\n\n/**\n * Private key in Bytes and WIF formats\n * @typedef {Object} PrivateKey\n * @property {Uint8Array} pkBytes - The unprocessed Private Key bytes.\n * @property {string} strWIF - The WIF encoded private key string.\n */\n\n/**\n * Network encode 32 bytes for a private key\n * @param {Uint8Array} pkBytes - 32 Bytes\n * @returns {Uint8Array} - The network-encoded Private Key bytes\n */\nexport function encodePrivkeyBytes(pkBytes) {\n const pkNetBytes = new Uint8Array(pkBytes.length + 2);\n pkNetBytes[0] = cChainParams.current.SECRET_KEY; // Private key prefix (1 byte)\n writeToUint8(pkNetBytes, pkBytes, 1); // Private key bytes (32 bytes)\n pkNetBytes[pkNetBytes.length - 1] = 1; // Leading digit (1 byte)\n return pkNetBytes;\n}\n\n/**\n * Generate a new private key OR encode an existing private key from raw bytes\n * @param {Uint8Array} pkBytesToEncode - Bytes to encode as a coin private key\n * @returns {PrivateKey} - The private key\n */\nexport function generateOrEncodePrivkey(pkBytesToEncode) {\n // Private Key Generation\n const pkBytes = pkBytesToEncode || getSafeRand();\n\n // Network Encoding\n const pkNetBytes = encodePrivkeyBytes(pkBytes);\n\n // Double SHA-256 hash\n const shaObj = dSHA256(pkNetBytes);\n\n // WIF Checksum\n const checksum = shaObj.slice(0, 4);\n const keyWithChecksum = new Uint8Array(34 + checksum.length);\n writeToUint8(keyWithChecksum, pkNetBytes, 0);\n writeToUint8(keyWithChecksum, checksum, 34);\n\n // Return both the raw bytes and the WIF format\n return { pkBytes, strWIF: bs58.encode(keyWithChecksum) };\n}\n\n/**\n * Compress an uncompressed Public Key in byte form\n * @param {Array | Uint8Array} pubKeyBytes - The uncompressed public key bytes\n * @returns {Array} The compressed public key bytes\n */\nfunction compressPublicKey(pubKeyBytes) {\n if (pubKeyBytes.length != 65)\n throw new Error('Attempting to compress an invalid uncompressed key');\n const x = pubKeyBytes.slice(1, 33);\n const y = pubKeyBytes.slice(33);\n\n // Compressed key is [key_parity + 2, x]\n return [y[31] % 2 === 0 ? 2 : 3, ...x];\n}\n\n/**\n * Derive a Secp256k1 network-encoded public key (coin address) from raw private or public key bytes\n * @param {Object} options - The object to deconstruct\n * @param {String} [options.publicKey] - The hex encoded public key. Can be both compressed or uncompressed\n * @param {Array | Uint8Array} [options.pkBytes] - An array of bytes containing the private key\n * @param {\"ENCODED\" | \"UNCOMPRESSED_HEX\" | \"COMPRESSED_HEX\"} options.output - Output\n * @return {String} the public key with the specified encoding\n */\nexport function deriveAddress({ pkBytes, publicKey, output = 'ENCODED' }) {\n if (!pkBytes && !publicKey) return null;\n const compress = output !== 'UNCOMPRESSED_HEX';\n // Public Key Derivation\n let pubKeyBytes = publicKey\n ? hexToBytes(publicKey)\n : nobleSecp256k1.getPublicKey(pkBytes, compress);\n\n if (output === 'UNCOMPRESSED_HEX') {\n if (pubKeyBytes.length !== 65) {\n // It's actually possible, but it's probably not something that we'll need\n throw new Error(\"Can't uncompress an already compressed key\");\n }\n return bytesToHex(pubKeyBytes);\n }\n\n if (pubKeyBytes.length === 65) {\n pubKeyBytes = compressPublicKey(pubKeyBytes);\n }\n\n if (pubKeyBytes.length != 33) {\n throw new Error('Invalid public key');\n }\n\n if (output === 'COMPRESSED_HEX') {\n return bytesToHex(pubKeyBytes);\n }\n\n // First pubkey SHA-256 hash\n const pubKeyHashing = sha256(new Uint8Array(pubKeyBytes));\n\n // RIPEMD160 hash\n const pubKeyHashRipemd160 = ripemd160(pubKeyHashing);\n\n // Network Encoding\n const pubKeyHashNetwork = new Uint8Array(pubKeyHashNetworkLen);\n pubKeyHashNetwork[0] = cChainParams.current.PUBKEY_ADDRESS;\n writeToUint8(pubKeyHashNetwork, pubKeyHashRipemd160, 1);\n\n // Double SHA-256 hash\n const pubKeyHashingSF = dSHA256(pubKeyHashNetwork);\n\n // Checksum\n const checksumPubKey = pubKeyHashingSF.slice(0, 4);\n\n // Public key pre-base58\n const pubKeyPreBase = new Uint8Array(pubPrebaseLen);\n writeToUint8(pubKeyPreBase, pubKeyHashNetwork, 0);\n writeToUint8(pubKeyPreBase, checksumPubKey, pubKeyHashNetworkLen);\n\n // Encode as Base58 human-readable network address\n return bs58.encode(pubKeyPreBase);\n}\n\n/**\n * Import a wallet (with it's private, public or encrypted data)\n * @param {object} options\n * @param {string | Array} options.newWif - The import data (if omitted, the UI input is accessed)\n * @param {boolean} options.fRaw - Whether the import data is raw bytes or encoded (WIF, xpriv, seed)\n * @param {boolean} options.isHardwareWallet - Whether the import is from a Hardware wallet or not\n * @param {boolean} options.fSavePublicKey - Whether to save the derived public key to disk (for View Only mode)\n * @param {boolean} options.fStartup - Whether the import is at Startup or at Runtime\n * @returns {Promise}\n */\nexport async function importWallet({\n newWif = false,\n fRaw = false,\n isHardwareWallet = false,\n fSavePublicKey = false,\n fStartup = false,\n} = {}) {\n // TODO: remove `walletConfirm`, it is useless as Accounts cannot be overriden, and multi-accounts will come soon anyway\n // ... just didn't want to add a huge whitespace change from removing the `if (walletConfirm) {` line\n const walletConfirm = true;\n if (walletConfirm) {\n if (isHardwareWallet) {\n // Firefox does NOT support WebUSB, thus cannot work with Hardware wallets out-of-the-box\n if (navigator.userAgent.includes('Firefox')) {\n return createAlert(\n 'warning',\n ALERTS.WALLET_FIREFOX_UNSUPPORTED,\n 7500\n );\n }\n const publicKey = await getHardwareWalletKeys(\n getDerivationPath(true)\n );\n // Errors are handled within the above function, so there's no need for an 'else' here, just silent ignore.\n if (!publicKey) return;\n\n // Derive our hardware address and import!\n await setMasterKey(new HardwareWalletMasterKey());\n\n // Hide the 'export wallet' button, it's not relevant to hardware wallets\n doms.domExportWallet.hidden = true;\n\n createAlert(\n 'info',\n tr(ALERTS.WALLET_HARDWARE_WALLET, [\n { hardwareWallet: strHardwareName },\n ]),\n 12500\n );\n } else {\n // If raw bytes: purely encode the given bytes rather than generating our own bytes\n if (fRaw) {\n newWif = generateOrEncodePrivkey(newWif).strWIF;\n\n // A raw import likely means non-user owned key (i.e: created via VanityGen), thus, we assume safety first and add an exit blocking listener\n addEventListener('beforeunload', beforeUnloadListener, {\n capture: true,\n });\n }\n\n // Select WIF from internal source OR user input (could be: WIF, Mnemonic or xpriv)\n const privateImportValue = newWif || doms.domPrivKey.value;\n const passphrase = doms.domPrivKeyPassword.value;\n doms.domPrivKey.value = '';\n doms.domPrivKeyPassword.value = '';\n\n if (await verifyMnemonic(privateImportValue)) {\n // Generate our masterkey via Mnemonic Phrase\n const seed = await mnemonicToSeed(\n privateImportValue,\n passphrase\n );\n await setMasterKey(new HdMasterKey({ seed }));\n } else {\n // Public Key Derivation\n try {\n if (isXPub(privateImportValue)) {\n await setMasterKey(\n new HdMasterKey({\n xpub: privateImportValue,\n })\n );\n } else if (privateImportValue.startsWith('xprv')) {\n await setMasterKey(\n new HdMasterKey({\n xpriv: privateImportValue,\n })\n );\n } else if (isStandardAddress(privateImportValue)) {\n await setMasterKey(\n new LegacyMasterKey({\n address: privateImportValue,\n })\n );\n } else {\n // Lastly, attempt to parse as a WIF private key\n const pkBytes = parseWIF(privateImportValue);\n\n // Import the raw private key\n await setMasterKey(new LegacyMasterKey({ pkBytes }));\n }\n } catch (e) {\n return createAlert(\n 'warning',\n ALERTS.FAILED_TO_IMPORT + '
' + e.message,\n 6000\n );\n }\n }\n }\n\n // Reaching here: the deserialisation was a full cryptographic success, so a wallet is now imported!\n fWalletLoaded = true;\n\n // Hide wipe wallet button if there is no private key\n if (masterKey.isViewOnly || masterKey.isHardwareWallet) {\n doms.domWipeWallet.hidden = true;\n if (await hasEncryptedWallet()) {\n doms.domRestoreWallet.hidden = false;\n }\n }\n\n // For non-HD wallets: hide the 'new address' button, since these are essentially single-address MPW wallets\n if (!masterKey.isHD) doms.domNewAddress.style.display = 'none';\n\n // Update the loaded address in the Dashboard\n getNewAddress({ updateGUI: true });\n\n // Display Text\n doms.domGuiWallet.style.display = 'block';\n doms.domDashboard.click();\n\n // Update identicon\n doms.domIdenticon.dataset.jdenticonValue = masterKey.getAddress(\n getDerivationPath()\n );\n jdenticon.update('#identicon');\n\n // Hide the encryption prompt if the user is using\n // a hardware wallet, or is view-only mode.\n if (!(isHardwareWallet || masterKey.isViewOnly)) {\n if (\n // If the wallet was internally imported (not UI pasted), like via vanity, display the encryption prompt\n (((fRaw && newWif.length) || newWif) &&\n !(await hasEncryptedWallet())) ||\n // If the wallet was pasted and is an unencrypted key, then display the encryption prompt\n !(await hasEncryptedWallet())\n ) {\n doms.domGenKeyWarning.style.display = 'block';\n } else if (await hasEncryptedWallet()) {\n // If the wallet was pasted and is an encrypted import, display the lock wallet UI\n doms.domWipeWallet.hidden = false;\n }\n } else {\n // Hide the encryption UI\n doms.domGenKeyWarning.style.display = 'none';\n }\n\n // Fetch state from explorer, if this import was post-startup\n if (getNetwork().enabled && !fStartup) {\n refreshChainData();\n getNetwork().getUTXOs();\n }\n\n // Hide all wallet starter options\n setDisplayForAllWalletOptions('none');\n }\n}\n\n/**\n * Set or replace the active Master Key with a new Master Key\n * @param {MasterKey} mk - The new Master Key to set active\n */\nexport async function setMasterKey(mk) {\n masterKey = mk;\n // Update the network master key\n await getNetwork().setMasterKey(masterKey);\n}\n\n// Wallet Generation\nexport async function generateWallet(noUI = false) {\n // TODO: remove `walletConfirm`, it is useless as Accounts cannot be overriden, and multi-accounts will come soon anyway\n // ... just didn't want to add a huge whitespace change from removing the `if (walletConfirm) {` line\n const walletConfirm = true;\n if (walletConfirm) {\n const mnemonic = generateMnemonic();\n\n const passphrase = !noUI\n ? await informUserOfMnemonic(mnemonic)\n : undefined;\n const seed = await mnemonicToSeed(mnemonic, passphrase);\n\n // Prompt the user to encrypt the seed\n await setMasterKey(new HdMasterKey({ seed }));\n fWalletLoaded = true;\n\n doms.domGenKeyWarning.style.display = 'block';\n // Add a listener to block page unloads until we are sure the user has saved their keys, safety first!\n addEventListener('beforeunload', beforeUnloadListener, {\n capture: true,\n });\n\n // Display the dashboard\n doms.domGuiWallet.style.display = 'block';\n setDisplayForAllWalletOptions('none');\n\n // Update identicon\n doms.domIdenticon.dataset.jdenticonValue = masterKey.getAddress(\n getDerivationPath()\n );\n jdenticon.update('#identicon');\n\n getNewAddress({ updateGUI: true });\n\n // Refresh the balance UI (why? because it'll also display any 'get some funds!' alerts)\n getBalance(true);\n getStakingBalance(true);\n }\n\n return masterKey;\n}\n\nexport async function verifyMnemonic(strMnemonic = '', fPopupConfirm = true) {\n const nWordCount = strMnemonic.trim().split(/\\s+/g).length;\n\n // Sanity check: Convert to lowercase\n strMnemonic = strMnemonic.toLowerCase();\n\n // Ensure it's a word count that makes sense\n if (nWordCount >= 12 && nWordCount <= 24) {\n if (!validateMnemonic(strMnemonic)) {\n // The reason we want to ask the user for confirmation is that the mnemonic\n // Could have been generated with another app that has a different dictionary\n return (\n fPopupConfirm &&\n (await confirmPopup({\n title: translation.popupSeedPhraseBad,\n html: translation.popupSeedPhraseBadNote,\n }))\n );\n } else {\n // Valid count and mnemonic\n return true;\n }\n } else {\n // Invalid count\n return false;\n }\n}\n\nfunction informUserOfMnemonic(mnemonic) {\n return new Promise((res, _) => {\n $('#mnemonicModal').modal({ keyboard: false });\n doms.domMnemonicModalContent.innerText = mnemonic;\n doms.domMnemonicModalButton.onclick = () => {\n res(doms.domMnemonicModalPassphrase.value);\n $('#mnemonicModal').modal('hide');\n\n // Wipe the mnemonic displays of sensitive data\n doms.domMnemonicModalContent.innerText = '';\n doms.domMnemonicModalPassphrase.value = '';\n };\n $('#mnemonicModal').modal('show');\n });\n}\n\nexport async function encryptWallet(strPassword = '') {\n // Encrypt the wallet WIF with AES-GCM and a user-chosen password - suitable for browser storage\n let strEncWIF = await encrypt(masterKey.keyToBackup, strPassword);\n if (!strEncWIF) return false;\n\n // Hide the encryption warning\n doms.domGenKeyWarning.style.display = 'none';\n\n // Prepare to Add/Update an account in the DB\n const cAccount = new Account({\n publicKey: await masterKey.keyToExport,\n encWif: strEncWIF,\n });\n\n // Incase of a \"Change Password\", we check if an Account already exists\n const database = await Database.getInstance();\n if (await database.getAccount()) {\n // Update the existing Account (new encWif) in the DB\n await database.updateAccount(cAccount);\n } else {\n // Add the new Account to the DB\n await database.addAccount(cAccount);\n }\n\n // Remove the exit blocker, we can annoy the user less knowing the key is safe in their database!\n removeEventListener('beforeunload', beforeUnloadListener, {\n capture: true,\n });\n}\n\nexport async function decryptWallet(strPassword = '') {\n // Check if there's any encrypted WIF available\n const database = await Database.getInstance();\n const { encWif: strEncWIF } = await database.getAccount();\n if (!strEncWIF || strEncWIF.length < 1) return false;\n\n // Prompt to decrypt it via password\n const strDecWIF = await decrypt(strEncWIF, strPassword);\n if (!strDecWIF || strDecWIF === 'decryption failed!') {\n if (strDecWIF)\n return createAlert('warning', ALERTS.INCORRECT_PASSWORD, 6000);\n } else {\n await importWallet({\n newWif: strDecWIF,\n // Save the public key to disk for View Only mode\n fSavePublicKey: true,\n });\n return true;\n }\n}\n\n/**\n * @returns {Promise} If the wallet has an encrypted database backup\n */\nexport async function hasEncryptedWallet() {\n const database = await Database.getInstance();\n const account = await database.getAccount();\n return !!account?.encWif;\n}\n\n// If the privateKey is null then the user connected a hardware wallet\nexport function hasHardwareWallet() {\n if (!masterKey) return false;\n return masterKey.isHardwareWallet == true;\n}\n\nexport async function hasWalletUnlocked(fIncludeNetwork = false) {\n if (fIncludeNetwork && !getNetwork().enabled)\n return createAlert('warning', ALERTS.WALLET_OFFLINE_AUTOMATIC, 5500);\n if (!masterKey) {\n return createAlert(\n 'warning',\n tr(ALERTS.WALLET_UNLOCK_IMPORT, [\n {\n unlock: (await hasEncryptedWallet())\n ? 'unlock '\n : 'import/create',\n },\n ]),\n 3500\n );\n } else {\n return true;\n }\n}\n\nfunction createAddressConfirmation(address) {\n return `${translation.popupHardwareAddrCheck} ${strHardwareName}.\n
${address}
`;\n}\n\nexport async function getNewAddress({\n updateGUI = false,\n verify = false,\n} = {}) {\n const [address, path] = await masterKey.getNewAddress();\n if (verify && masterKey.isHardwareWallet) {\n // Generate address to present to the user without asking to verify\n const confAddress = await confirmPopup({\n title: ALERTS.CONFIRM_POPUP_VERIFY_ADDR,\n html: createAddressConfirmation(address),\n resolvePromise: masterKey.getAddress(path, { verify }),\n });\n if (address !== confAddress) {\n throw new Error('User did not verify address');\n }\n }\n\n // If we're generating a new address manually, then render the new address in our Receive Modal\n if (updateGUI) {\n guiRenderCurrentReceiveModal();\n }\n\n return [address, path];\n}\n\nexport let cHardwareWallet = null;\nexport let strHardwareName = '';\nlet transport;\nasync function getHardwareWalletKeys(\n path,\n xpub = false,\n verify = false,\n _attempts = 0\n) {\n try {\n // Check if we haven't setup a connection yet OR the previous connection disconnected\n if (!cHardwareWallet || transport._disconnectEmitted) {\n transport = await TransportWebUSB.create();\n cHardwareWallet = new AppBtc({ transport, currency: 'PIVX' });\n }\n\n // Update device info and fetch the pubkey\n strHardwareName =\n transport.device.manufacturerName +\n ' ' +\n transport.device.productName;\n\n // Prompt the user in both UIs\n if (verify) createAlert('info', ALERTS.WALLET_CONFIRM_L, 3500);\n const cPubKey = await cHardwareWallet.getWalletPublicKey(path, {\n verify,\n format: 'legacy',\n });\n\n if (xpub) {\n return createXpub({\n depth: 3,\n childNumber: 2147483648,\n chainCode: cPubKey.chainCode,\n publicKey: cPubKey.publicKey,\n });\n } else {\n return cPubKey.publicKey;\n }\n } catch (e) {\n if (e.message.includes('denied by the user')) {\n // User denied an operation\n return false;\n }\n\n // If there's no device, nudge the user to plug it in.\n if (e.message.toLowerCase().includes('no device selected')) {\n createAlert('info', ALERTS.WALLET_NO_HARDWARE, 10000);\n return false;\n }\n\n // If the device is unplugged, or connection lost through other means (such as spontanious device explosion)\n if (e.message.includes(\"Failed to execute 'transferIn'\")) {\n createAlert(\n 'info',\n tr(ALERTS.WALLET_HARDWARE_CONNECTION_LOST, [\n {\n hardwareWallet: strHardwareName,\n },\n ]),\n 10000\n );\n return false;\n }\n if (_attempts < 10) {\n // This is an ugly hack :(\n // in the event where multiple parts of the code decide to ask for an address, just\n // Retry at most 10 times waiting 200ms each time\n await sleep(200);\n return await getHardwareWalletKeys(\n path,\n xpub,\n verify,\n _attempts + 1\n );\n }\n\n // If the ledger is busy, just nudge the user.\n if (e.message.includes('is busy')) {\n createAlert(\n 'info',\n tr(ALERTS.WALLET_HARDWARE_BUSY, [\n {\n hardwareWallet: strHardwareName,\n },\n ]),\n 7500\n );\n return false;\n }\n\n // Check if this is an expected error\n if (!e.statusCode || !LEDGER_ERRS.has(e.statusCode)) {\n console.error(\n 'MISSING LEDGER ERROR-CODE TRANSLATION! - Please report this below error on our GitHub so we can handle it more nicely!'\n );\n console.error(e);\n }\n\n // Translate the error to a user-friendly string (if possible)\n createAlert(\n 'warning',\n tr(ALERTS.WALLET_HARDWARE_ERROR, [\n {\n hardwareWallet: strHardwareName,\n },\n {\n error: LEDGER_ERRS.get(e.statusCode),\n },\n ]),\n 5500\n );\n\n return false;\n }\n}\n","import { deriveAddress } from './wallet.js';\nimport { getSafeRand } from './misc.js';\n\nonmessage = function (_evt) {\n while (true) {\n const cKeypair = {};\n cKeypair.priv = getSafeRand();\n\n cKeypair.pub = deriveAddress({ pkBytes: cKeypair.priv });\n postMessage(cKeypair);\n }\n};\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n// the startup function\n__webpack_require__.x = () => {\n\t// Load entry module and return exports\n\t// This entry module depends on other loaded chunks and execution need to be delayed\n\tvar __webpack_exports__ = __webpack_require__.O(undefined, [621,369], () => (__webpack_require__(56691)))\n\t__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n\treturn __webpack_exports__;\n};\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"./\" + chunkId + \".mpw.js\";\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript)\n\t\tscriptUrl = document.currentScript.src\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) scriptUrl = scripts[scripts.length - 1].src\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","__webpack_require__.b = self.location + \"\";\n\n// object to store loaded chunks\n// \"1\" means \"already loaded\"\nvar installedChunks = {\n\t56: 1\n};\n\n// importScripts chunk loading\nvar installChunk = (data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\tfor(var moduleId in moreModules) {\n\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t}\n\t}\n\tif(runtime) runtime(__webpack_require__);\n\twhile(chunkIds.length)\n\t\tinstalledChunks[chunkIds.pop()] = 1;\n\tparentChunkLoadingFunction(data);\n};\n__webpack_require__.f.i = (chunkId, promises) => {\n\t// \"1\" is the signal for \"already loaded\"\n\tif(!installedChunks[chunkId]) {\n\t\tif(true) { // all chunks have JS\n\t\t\timportScripts(__webpack_require__.p + __webpack_require__.u(chunkId));\n\t\t}\n\t}\n};\n\nvar chunkLoadingGlobal = self[\"webpackChunkMPW\"] = self[\"webpackChunkMPW\"] || [];\nvar parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);\nchunkLoadingGlobal.push = installChunk;\n\n// no HMR\n\n// no HMR manifest","// run startup\nvar __webpack_exports__ = __webpack_require__.x();\n"],"names":["deferred","leafPrototypes","getProto","next","bytes","Buffer","toString","current","main","name","collateralInSats","isTestnet","TICKER","PUBKEY_PREFIX","STAKING_PREFIX","PUBKEY_ADDRESS","SECRET_KEY","BIP44_TYPE","BIP44_TYPE_LEDGER","PROTOCOL_VERSION","MASTERNODE_PORT","Explorers","url","Nodes","Consensus","UPGRADE_V6_0","undefined","budgetCycleBlocks","proposalFee","maxPaymentCycles","maxPayment","testnet","MarketSource","cData","strName","strEndpoint","async","this","Object","keys","length","fetch","json","e","console","warn","constructor","super","strCurrency","ensureCacheExists","market_data","current_price","val","Array","isArray","nDisplayDecimals","hit","time_to_sync","transaction","freeze","FALSE","PUSHDATA1","PUSHDATA2","PUSHDATA4","RESERVED","TRUE","NOP","VER","IF","NOTIF","VERIF","VERNOTIF","ELSE","ENDIF","VERIFY","RETURN","TOALTSTACK","FROMALTSTACK","IFDUP","DEPTH","DROP","DUP","NIP","OVER","PICK","ROLL","ROT","SWAP","TUCK","CAT","SUBSTR","LEFT","RIGHT","SIZE","INVERT","AND","OR","XOR","EQUAL","EQUALVERIFY","RESERVED1","RESERVED2","NEGATE","ABS","NOT","ADD","SUB","MUL","DIV","MOD","LSHIFT","RSHIFT","BOOLAND","BOOLOR","NUMEQUAL","NUMEQUALVERIFY","NUMNOTEQUAL","LESSTHAN","GREATERTHAN","LESSTHANOREQUAL","GREATERTHANOREQUAL","MIN","MAX","WITHIN","RIPEMD160","SHA1","SHA256","HASH160","HASH256","CODESEPARATOR","CHECKSIG","CHECKSIGVERIFY","CHECKMULTISIG","CHECKMULTISIGVERIFY","NOP1","NOP2","CHECKLOCKTIMEVERIFY","NOP3","NOP4","NOP5","NOP6","NOP7","NOP8","NOP9","NOP10","ZEROCOINMINT","ZEROCOINSPEND","ZEROCOINPUBLICSPEND","CHECKCOLDSTAKEVERIFY_LOF","CHECKCOLDSTAKEVERIFY","INVALIDOPCODE","static","db","close","masternode","_masterKey","store","objectStore","put","delete","promo","code","account","Account","error","createAlert","cDBAccount","strKey","isSameType","get","allowDeletion","getAccount","isEmpty","publicKey","cAccount","Masternode","getAll","map","PromoWallet","Settings","settings","oldSettings","getSettings","localStorage","analytics","explorer","node","translation","displayCurrency","setSettings","JSON","parse","addMasternode","ALERTS","MIGRATION_MASTERNODE_FAILURE","encwif","localProposals","encWif","addAccount","MIGRATION_ACCOUNT_FAILURE","confirmPopup","title","MIGRATION_ACCOUNT_FAILURE_TITLE","html","MIGRATION_ACCOUNT_FAILURE_HTML","sanitizeHTML","database","openDB","upgrade","oldVersion","log","createObjectStore","blocking","alert","window","location","reload","Map","cChainParams","instance","set","create","nSize","crypto","getRandomValues","Uint8Array","arr","pos","arrLen","strERR","Error","i","type","message","timeout","domAlert","document","createElement","typeIcon","classList","add","setTimeout","style","opacity","zIndex","innerHTML","destroy","clearTimeout","timer","remove","addEventListener","beautifyNumber","strNumber","strDecFontSize","includes","arrNumParts","split","strFontSize","eventEmitter","EventEmitter","id","path","sats","script","vin","vout","height","status","isDelegate","isReward","equalsUTXO","cUTXO","UTXOs","subscribeToNetwork","getUTXO","out","find","nBlocks","ms","Promise","res","_","removeUTXO","isAlreadyStored","some","getUTXOsByState","nState","filter","removeFromState","cNewUTXO","arrPendingUTXOs","addUTXO","newUTXO","updateUTXO","cStakeInput","txid","push","utxo","PENDING","CONFIRMED","autoRemoveUTXO","REMOVED","removeWithDelay","autoRemoveUTXOs","arrUTXOs","getConfirmed","getStandardUTXOs","getDelegatedUTXOs","getBalance","cMasternode","collateralTxId","outidx","reduce","a","b","cachedBlockCount","getDelegatedBalance","on","utxos","getUTXOFullInfo","TextEncoder","TextDecoder","updateTicker","domGuiBalanceValueCurrency","innerText","domGuiStakingValueCurrency","domSendAmountValueCurrency","domSendAmountCoinsTicker","domStakeAmountValueCurrency","domStakeAmountCoinsTicker","domUnstakeAmountValueCurrency","domUnstakeAmountCoinsTicker","updatePriceDisplay","domValue","fCold","nPrice","nCurrencyValue","nValue","cLocale","nAmount","Intl","supportedValuesOf","currency","currencyDisplay","maximumFractionDigits","minimumFractionDigits","optimiseCurrencyLocale","toLocaleString","updateGUI","nBalance","strBal","toFixed","nLen","domGuiBalance","domAvailToDelegate","domGuiBalanceValue","domGuiBalanceStaking","domAvailToUndelegate","domGuiStakingValue","errorHandler","text","element","reason","pkBytes","output","compress","pubKeyBytes","str","x","slice","compressPublicKey","pubKeyHashing","pubKeyHashRipemd160","ripemd160","pubKeyHashNetwork","buff","checksumPubKey","pubKeyPreBase","pubKeyHashNetworkLen","onmessage","_evt","cKeypair","priv","pub","postMessage","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","module","loaded","__webpack_modules__","call","m","__webpack_exports__","O","result","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","j","every","key","splice","r","n","getter","__esModule","d","getPrototypeOf","obj","t","value","mode","then","ns","def","indexOf","getOwnPropertyNames","forEach","definition","o","defineProperty","enumerable","f","chunkId","all","promises","u","miniCssF","g","globalThis","Function","prop","prototype","hasOwnProperty","Symbol","toStringTag","nmd","paths","children","scriptUrl","importScripts","currentScript","src","scripts","getElementsByTagName","replace","p","self","installedChunks","chunkLoadingGlobal","parentChunkLoadingFunction","bind","data","moreModules","runtime","pop"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"./56.mpw.js","mappings":"kBAAIA,ECCAC,EADAC,ECAAC,E,0DCOG,SAAS,EAAWC,GACvB,OAAO,EAAAC,OAAA,KAAYD,GAAOE,SAAS,MACvC,C,kCCNO,MAGM,EAAO,IAAM,EAab,EAAe,CACxBC,QAAS,KACTC,KAAM,CACFC,KAAM,UACNC,iBAAkB,KAClBC,WAAW,EACXC,OAAQ,MACRC,cAAe,CAAC,KAChBC,eAAgB,IAChBC,eAAgB,GAChBC,WAAY,IACZC,WAAY,IACZC,kBAAmB,GACnBC,iBAAkB,MAClBC,gBAAiB,MAEjBC,UAAW,CAEP,CAAEZ,KAAM,UAAWa,IAAK,gCACxB,CAAEb,KAAM,YAAaa,IAAK,yBAC1B,CAAEb,KAAM,UAAWa,IAAK,iCAE5BC,MAAO,CAAC,CAAEd,KAAM,UAAWa,IAAK,oCAChCE,UAAW,CAEPC,kBAAcC,GAElBC,kBAAmB,MACnBC,YAAa,IACbC,iBAAkB,EAClBC,WAAY,QAEhBC,QAAS,CACLtB,KAAM,UACNC,iBAAkB,KAClBC,WAAW,EACXC,OAAQ,OACRC,cAAe,CAAC,IAAK,KACrBC,eAAgB,IAChBC,eAAgB,IAChBC,WAAY,IACZC,WAAY,EACZC,kBAAmB,EACnBC,iBAAkB,MAClBC,gBAAiB,MAEjBC,UAAW,CAEP,CAAEZ,KAAM,UAAWa,IAAK,gCAE5BC,MAAO,CAAC,CAAEd,KAAM,UAAWa,IAAK,oCAChCE,UAAW,CAEPC,kBAAcC,GAElBC,kBAAmB,IACnBC,YAAa,IACbC,iBAAkB,GAClBC,WAAY,QAIpB,EAAavB,QAAU,EAAaC,K,wBCnE7B,MAAMwB,EAETC,MAAQ,CAAC,EAGTC,QAAU,GAGVC,YAAc,GAKdC,0BACSC,KAAKJ,OAAUK,OAAOC,KAAKF,KAAKJ,OAAOO,cAAcH,KAAKI,OACnE,CAMAL,cACI,IACI,OAAQC,KAAKJ,kBAAqBQ,MAAMJ,KAAKF,cAAcO,MAK/D,CAJE,MAAOC,GAGL,OAFAC,EAAQC,KAAK,sCACbD,EAAQC,KAAKF,GACN,IACX,CACJ,ECTG,IAKI,EAAc,MAKd,EAAU,IDKd,cAAwBX,EAC3Bc,cACIC,QACAV,KAAKH,QAAU,YACfG,KAAKF,YA5CT,yJA6CA,CAOAC,eAAeY,GAEX,aADMX,KAAKY,oBACJZ,KAAKJ,OAAOiB,aAAaC,cAAcH,IAAgB,CAClE,CAMAZ,sBAEI,aADMC,KAAKY,oBEwYJ,OAFSG,EFrYAf,KAAKJ,QEwYb,KAARmB,GACCC,MAAMC,QAAQF,IAAuB,IAAfA,EAAIZ,QACX,iBAARY,GAAgD,IAA5Bd,OAAOC,KAAKa,GAAKZ,OFxYvC,GADAF,OAAOC,KAAKF,KAAKJ,MAAMiB,YAAYC,eEoY1C,IAAiBC,CFlYpB,GCrBOG,GARY,uBAEJ,mBAMW,GAmEnB,EAAQ,CAEfC,IAAK,yDACLC,aAAc,2DACdC,YACI,2FAGiBpB,OAAOC,KAAK,G,SEgBrCD,OAAOqB,OAjJW,CAEd,EAAG,EACHC,MAAO,EACPC,UAAW,GACXC,UAAW,GACXC,UAAW,GACX,UAAW,GACXC,SAAU,GACV,EAAG,GACHC,KAAM,GACN,EAAG,GACH,EAAG,GACH,EAAG,GACH,EAAG,GACH,EAAG,GACH,EAAG,GACH,EAAG,GACH,EAAG,GACH,GAAI,GACJ,GAAI,GACJ,GAAI,GACJ,GAAI,GACJ,GAAI,GACJ,GAAI,GACJ,GAAI,GAGJC,IAAK,GACLC,IAAK,GACLC,GAAI,GACJC,MAAO,IACPC,MAAO,IACPC,SAAU,IACVC,KAAM,IACNC,MAAO,IACPC,OAAQ,IACRC,OAAQ,IAGRC,WAAY,IACZC,aAAc,IACd,QAAS,IACT,OAAQ,IACR,OAAQ,IACR,QAAS,IACT,OAAQ,IACR,QAAS,IACTC,MAAO,IACPC,MAAO,IACPC,KAAM,IACNC,IAAK,IACLC,IAAK,IACLC,KAAM,IACNC,KAAM,IACNC,KAAM,IACNC,IAAK,IACLC,KAAM,IACNC,KAAM,IAGNC,IAAK,IACLC,OAAQ,IACRC,KAAM,IACNC,MAAO,IACPC,KAAM,IAGNC,OAAQ,IACRC,IAAK,IACLC,GAAI,IACJC,IAAK,IACLC,MAAO,IACPC,YAAa,IACbC,UAAW,IACXC,UAAW,IAGX,OAAQ,IACR,OAAQ,IACR,OAAQ,IACR,OAAQ,IACRC,OAAQ,IACRC,IAAK,IACLC,IAAK,IACL,YAAa,IAEbC,IAAK,IACLC,IAAK,IACLC,IAAK,IACLC,IAAK,IACLC,IAAK,IACLC,OAAQ,IACRC,OAAQ,IAERC,QAAS,IACTC,OAAQ,IACRC,SAAU,IACVC,eAAgB,IAChBC,YAAa,IACbC,SAAU,IACVC,YAAa,IACbC,gBAAiB,IACjBC,mBAAoB,IACpBC,IAAK,IACLC,IAAK,IAELC,OAAQ,IAGRC,UAAW,IACXC,KAAM,IACNC,OAAQ,IACRC,QAAS,IACTC,QAAS,IACTC,cAAe,IACfC,SAAU,IACVC,eAAgB,IAChBC,cAAe,IACfC,oBAAqB,IAGrBC,KAAM,IACNC,KAAM,IACNC,oBAAqB,IACrBC,KAAM,IACNC,KAAM,IACNC,KAAM,IACNC,KAAM,IACNC,KAAM,IACNC,KAAM,IACNC,KAAM,IACNC,MAAO,IAGPC,aAAc,IACdC,cAAe,IACfC,oBAAqB,IAGrBC,yBAA0B,IAC1BC,qBAAsB,IAEtBC,cAAe,M,sFC1HZ,MAAM,EAMTC,eAAiB,KAKjB,GAEAzG,aAAY,GAAE0G,IACVnH,MAAK,EAAMmH,CACf,CAEAC,QACIpH,MAAK,EAAIoH,QACTpH,MAAK,EAAM,IACf,CAOAD,oBAAoBsH,EAAYC,GAC5B,MAAMC,EAAQvH,MAAK,EACdqB,YAAY,cAAe,aAC3BmG,YAAY,qBAEXD,EAAME,IAAIJ,EAAY,aAChC,CAKAtH,uBAAuBuH,GACnB,MAAMC,EAAQvH,MAAK,EACdqB,YAAY,cAAe,aAC3BmG,YAAY,qBACXD,EAAMG,OAAO,aACvB,CAMA3H,eAAe4H,GACX,MAAMJ,EAAQvH,MAAK,EACdqB,YAAY,SAAU,aACtBmG,YAAY,gBAEXD,EAAME,IAAIE,EAAOA,EAAMC,KACjC,CAKA7H,kBAAkB4H,GACd,MAAMJ,EAAQvH,MAAK,EACdqB,YAAY,SAAU,aACtBmG,YAAY,gBACXD,EAAMG,OAAOC,EACvB,CAQA5H,iBAAiB8H,GAEb,KAAMA,aAAmBC,SAUrB,OATA,iBAAQC,MACJ,sEAEJ,iBAAQA,MAAMF,GACd,iBAAQE,MAAM,iCACdC,YACI,UACA,wIAEG,EAIX,MAAMC,EAAa,IAAIH,QAKvB,IAAK,MAAMI,KAAUjI,OAAOC,KAAK+H,GAExBE,WAAWN,EAAQK,GAASD,EAAWC,IAU5CD,EAAWC,GAAUL,EAAQK,GATzB,iBAAQH,MACJ,yBACIG,EACA,iFAShB,MAAMX,EAAQvH,MAAK,EACdqB,YAAY,WAAY,aACxBmG,YAAY,YAGjB,SAAUD,EAAMa,IAAI,WAChB,OAAO,iBAAQL,MACX,2DAIFR,EAAME,IAAIQ,EAAY,UAChC,CAeAlI,oBAAoB8H,EAASQ,GAAgB,GAEzC,KAAMR,aAAmBC,SAUrB,OATA,iBAAQC,MACJ,yEAEJ,iBAAQA,MAAMF,GACd,iBAAQE,MAAM,iCACdC,YACI,UACA,sJAEG,EAIX,MAAMC,QAAmBjI,KAAKsI,aAI9B,IAAKL,EAUD,OATA,iBAAQF,MACJ,kFAEJ,iBAAQA,MAAMF,GACd,iBAAQE,MAAM,+BACdC,YACI,UACA,iIAEG,EAMX,IAAK,MAAME,KAAUjI,OAAOC,KAAK+H,GAExBE,WAAWN,EAAQK,GAASD,EAAWC,KAWvCG,GAAiBE,QAAQV,EAAQK,MAGtCD,EAAWC,GAAUL,EAAQK,IAbzB,iBAAQH,MACJ,4BACIG,EACA,iFAahB,MAAMX,EAAQvH,MAAK,EACdqB,YAAY,WAAY,aACxBmG,YAAY,kBAEXD,EAAME,IAAIQ,EAAY,UAChC,CAOAlI,qBAAoB,UAAEyI,IAClB,MAAMjB,EAAQvH,MAAK,EACdqB,YAAY,WAAY,aACxBmG,YAAY,kBAEXD,EAAMG,OAAO,UACvB,CAQA3H,mBACI,MAAMwH,EAAQvH,MAAK,EACdqB,YAAY,WAAY,YACxBmG,YAAY,YACXS,QAAmBV,EAAMa,IAAI,WAGnC,IAAKH,EAAY,OAAO,KAGxB,MAAMQ,EAAW,IAAIX,QACrB,IAAK,MAAMI,KAAUjI,OAAOC,KAAKuI,GAExBN,WAAWF,EAAWC,GAASO,EAASP,IAU7CO,EAASP,GAAUD,EAAWC,GAT1B,iBAAQH,MACJ,yBACIG,EACA,kFAUhB,OAAOO,CACX,CAKA1I,oBAAoBuH,GAChB,MAAMC,EAAQvH,MAAK,EACdqB,YAAY,cAAe,YAC3BmG,YAAY,eACjB,OAAO,IAAIkB,iBAAiBnB,EAAMa,IAAI,cAC1C,CAKArI,qBACI,MAAMwH,EAAQvH,MAAK,EACdqB,YAAY,SAAU,YACtBmG,YAAY,UAEjB,aAAcD,EAAMoB,UAAUC,KAAKjB,GAAU,IAAIkB,YAAYlB,IACjE,CAKA5H,oBACI,MAAMwH,EAAQvH,MAAK,EACdqB,YAAY,WAAY,YACxBmG,YAAY,YACjB,OAAO,IAAIsB,eAAevB,EAAMa,IAAI,YACxC,CAMArI,kBAAkBgJ,GACd,MAAMC,QAAoBhJ,KAAKiJ,cACzB1B,EAAQvH,MAAK,EACdqB,YAAY,WAAY,aACxBmG,YAAY,kBACXD,EAAME,IACR,IACOuB,KACAD,GAEP,WAER,CAMAhJ,UACI,GAA4B,IAAxBmJ,aAAa/I,OAAc,OAC/B,MAAM4I,EAAW,IAAID,SAAS,CAC1BK,UAAWD,aAAaC,UACxBC,SAAUF,aAAaE,SACvBC,KAAMH,aAAaG,KACnBC,YAAaJ,aAAaI,YAC1BC,gBAAiBL,aAAaK,kBAIlC,SAFMvJ,KAAKwJ,YAAYT,GAEnBG,aAAa7B,WACb,IACI,MAAMA,EAAaoC,KAAKC,MAAMR,aAAa7B,kBACrCrH,KAAK2J,cAActC,EAI7B,CAHE,MAAO/G,GACL,iBAAQyH,MAAMzH,GACd0H,YAAY,UAAW4B,OAAOC,6BAClC,CAGJ,GAAIX,aAAaY,QAAUZ,aAAaV,UACpC,IACI,MAAMuB,EAAiBN,KAAKC,MACxBR,aAAaa,gBAAkB,MAI7BtB,EAAW,IAAIX,QAAQ,CACzBU,UAAWU,aAAaV,UACxBwB,OAAQd,aAAaY,OACrBC,eAAgBA,UAId/J,KAAKiK,WAAWxB,EAc1B,CAbE,MAAOnI,GACL,iBAAQyH,MAAMzH,GACd0H,YAAY,UAAW4B,OAAOM,2BAC1BhB,aAAaY,cACPK,aAAa,CACfC,MAAOd,YAAYe,gCACnBC,KAAM,GACFhB,YAAYiB,kEACoBC,aAChCtB,aAAaY,mBAI7B,CAER,CAEA5C,oBAAoB9I,GAEhB,MAAMqM,EAAW,IAAI,EAAS,CAAEtD,GAAI,OAC9BA,QAAWuD,OAAO,OAAOtM,IAzWb,EAyWiC,CAC/CuM,QAAS,CAACxD,EAAIyD,KACV,iBAAQC,IACJ,sBAAwBD,EAAxB,SAEc,GAAdA,IACAzD,EAAG2D,kBAAkB,eACrB3D,EAAG2D,kBAAkB,YACrB3D,EAAG2D,kBAAkB,aAKrBF,GAAc,GACdzD,EAAG2D,kBAAkB,SACzB,EAEJC,SAAU,KAINN,EAASrD,QACT4D,MAAM,wBACNC,OAAOC,SAASC,QAAQ,IAOhC,OAJAV,GAAS,EAAMtD,EAIRsD,CACX,CAMAvD,SAAoB,IAAIkE,IAKxBlE,2BACI,MAAM9I,EAAOiN,aAAanN,QAAQE,KAC5BkN,EAAWtL,MAAK,EAAWoI,IAAIhK,GAKrC,OAJKkN,GAAaA,GAAS,GACvBtL,MAAK,EAAWuL,IAAInN,QAAY,EAASoN,OAAOpN,IAG7C4B,MAAK,EAAWoI,IAAIhK,EAC/B,E,SC5ZG,IAAI,EAAc,CAAC,EHKnB,SAAS,EAAYqN,EAAQ,IAChC,OAAOC,OAAOC,gBAAgB,IAAIC,WAAWH,GACjD,CAqBO,SAAS,EAAaI,EAAK9N,EAAO+N,GACrC,MAAMC,EAASF,EAAI1L,OAEnB,GAAI4L,EAASD,EAAM/N,EAAMoC,OAAS,EAAG,CACjC,MAAM6L,EACF,iCACCD,EAASD,EAAM/N,EAAMoC,QACtB,4DAEJ,MADA,EAAY,UAAW6L,EAAQ,KACzBC,MAAMD,EAChB,CACA,IAAIE,EAAI,EACR,KAAOJ,EAAMC,GAAQF,EAAIC,KAAS/N,EAAMmO,IAC5C,CAqCO,SAAS,EAAYC,EAAMC,EAASC,EAAU,GACjD,MAAMC,EAAWC,SAASC,cAAc,OAWxC,IAAIC,EACJ,OAXAH,EAASI,UAAUC,IAAI,iBACvBL,EAASI,UAAUC,IAAIR,GACvBS,YAAW,KACPN,EAASO,MAAMC,QAAU,IACzBR,EAASO,MAAME,OAAS,SACxBT,EAASI,UAAUC,IAAI,cACvBL,EAASI,UAAUC,IAAI,SAAS,GACjC,KAIKR,GACJ,IAAK,UACDM,EAAW,iBACX,MACJ,IAAK,OACDA,EAAW,UACX,MACJ,QAGIA,EAAW,WAKnBH,EAASU,UAAY,uCACWb,8BACZM,oEAGdL,gBAENE,EAASW,QAAU,KAEfC,aAAaZ,EAASa,OACtBb,EAASO,MAAMC,QAAU,IACzBF,YAAW,KACPN,EAASc,QAAQ,GAClB,IAAI,EAGXd,EAASe,iBAAiB,QAASf,EAASW,SAExCZ,EAAU,IAAGC,EAASa,MAAQP,WAAWN,EAASW,QAASZ,IAC/D,0BAA6BC,EACjC,CAwPO,SAASgB,EAAeC,EAAWC,EAAiB,IAIvD,GAHyB,iBAAdD,IAAwBA,EAAYA,EAAUtP,aAGpDsP,EAAUE,SAAS,KAAM,OAAOF,EAGrC,MAAMG,EAAcH,EAAUI,MAAM,KAG9BC,EAAcJ,EAAiB,cAAgBA,EAAiB,GACtE,MAAO,GAAGE,EAAY,iCAAiCE,OAAiBF,EAAY,WACxF,C,2BI/YA,MAAMG,EAAe,I,SAAIC,c,wBCWlB,MAAM,EAcTrN,aAAY,GACRsN,EAAE,KACFC,EAAI,KACJC,EAAI,OACJC,EAAM,IACNC,EAAM,GAAE,KACRC,EAAI,OACJC,EAAM,OACNC,EAAM,WACNC,GAAa,EAAK,SAClBC,GAAW,GACX,CAAC,GAGDxO,KAAK+N,GAAKA,EAIV/N,KAAKgO,KAAOA,EAIZhO,KAAKiO,KAAOA,EAIZjO,KAAKkO,OAASA,EAIdlO,KAAKmO,IAAMA,EAIXnO,KAAKoO,KAAOA,EAIZpO,KAAKqO,OAASA,EAIdrO,KAAKsO,OAASA,EAIdtO,KAAKuO,WAAaA,EAIlBvO,KAAKwO,SAAWA,CACpB,CAOAC,WAAWC,GACP,OACI1O,KAAK+N,KAAOW,EAAMX,IAClB/N,KAAKoO,OAASM,EAAMN,MACpBpO,KAAKsO,SAAWI,EAAMJ,MAE9B,EAIG,MAAM,EACT7N,cAKIT,KAAK2O,MAAQ,GACb3O,KAAK4O,oBACT,CAGA1H,iBAAmB,EAGnBA,eAAiB,EAGjBA,eAAiB,EAOjB2H,QAAQd,EAAIe,GACR,OAAO9O,KAAK2O,MAAMI,MACbL,GAAUA,EAAMX,KAAOA,GAAMW,EAAMN,OAASU,GAErD,CAOA/O,sBAAsBiP,EAASN,GL6V5B,IAAeO,UK5VQ,GAAVD,EAAe,IL6VxB,IAAIE,SAAQ,CAACC,EAAKC,IAAMxC,WAAWuC,EAAKF,MK5V3CjP,KAAKqP,WAAWX,EACpB,CAUAY,iBAAgB,GAAEvB,EAAE,KAAEK,EAAI,OAAEE,IACxB,OAAOtO,KAAK2O,MAAMY,MACbb,GACGA,EAAMX,KAAOA,GACbW,EAAMN,OAASA,KACbE,GAAUI,EAAMJ,SAAWA,IAEzC,CAOAkB,gBAAgBC,GACZ,OAAOzP,KAAK2O,MAAMe,QAAQhB,GAAUA,EAAMJ,SAAWmB,GACzD,CAOAE,gBAAgBC,EAAUH,GACtB,MAAMI,EAAkB7P,KAAKwP,gBAAgBC,GAE7C,IAAK,MAAMf,KAASmB,EAEhB,GAAInB,EAAMX,KAAO6B,EAAS7B,IAAMW,EAAMN,OAASwB,EAASxB,KAAM,CAE1DpO,KAAKqP,WAAWX,GAChB,KACJ,CAER,CAMAoB,SAAQ,GACJ/B,EAAE,KACFC,EAAI,KACJC,EAAI,OACJC,EAAM,IACNC,EAAG,KACHC,EAAI,OACJC,EAAM,OACNC,EAAM,WACNC,EAAU,SACVC,IAEA,MAAMuB,EAAU,IAAI,EAAK,CACrBhC,KACAC,OACAC,OACAC,SACAC,MACAC,OACAC,SACAC,SACAC,aACAC,aAGJ,GAAIxO,KAAKsP,gBAAgB,CAAEvB,KAAIK,SAC3BpO,KAAKgQ,WAAW,CAAEjC,KAAIK,aACnB,CAEH,GAAII,GAA4B,IAAhBL,GAAKhO,OAAc,CAC/B,MAAM8P,EAAcjQ,KAAK6O,QAAQV,EAAI,GAAG+B,KAAM/B,EAAI,GAAGC,MAGjD6B,GACAjQ,KAAKqP,WAAWY,EAExB,CACAjQ,KAAK2O,MAAMwB,KAAKJ,EACpB,CAGA,GAAW,GACX,GAAkB,EACtB,CASAC,YAAW,GAAEjC,EAAE,KAAEK,IAOb,MAAMM,EAAQ1O,KAAK2O,MAAMI,MACpBqB,GAASA,EAAKrC,KAAOA,GAAMqC,EAAKhC,MAAQA,IAErCM,EAAMJ,SACL,EAAQ+B,UACT3B,EAAMJ,OAAS,EAAQgC,WAG/B,GAAW,GACX,GAAkB,EACtB,CAMAjB,WAAWX,GACP1O,KAAK2O,MAAQ3O,KAAK2O,MAAMe,QAAQU,IAAUA,EAAK3B,WAAWC,IAC9D,CAQA6B,gBAAe,GAAExC,EAAE,KAAEK,IACjB,IAAK,MAAMM,KAAS1O,KAAK2O,MAErB,GAAID,EAAMX,KAAOA,GAAMW,EAAMN,OAASA,EAGlC,OAFAM,EAAMJ,OAAS,EAAQkC,aACvBxQ,KAAKyQ,gBAAgB,GAAI/B,GAIjC,EAAQ3G,MACJ,gCACIgG,EACA,KACAK,EACA,sBAEZ,CAMAsC,gBAAgBC,GACZ,IAAK,MAAMf,KAAYe,EACnB,IAAK,MAAMjC,KAAS1O,KAAK2O,MAErB,GAAID,EAAMD,WAAWmB,GAAW,CAC5BlB,EAAMJ,OAAS,EAAQkC,QACvBxQ,KAAKyQ,gBAAgB,GAAI/B,GACzB,KACJ,CAGZ,CAMAkC,eACI,OAAO5Q,KAAKwP,gBAAgB,EAAQc,UACxC,CAMAO,mBACI,OAAO7Q,KAAK2O,MAAMe,QACbhB,GAAUA,EAAMJ,SAAW,EAAQkC,UAAY9B,EAAMH,YAE9D,CAMAuC,oBACI,OAAO9Q,KAAK2O,MAAMe,QACbhB,GAAUA,EAAMJ,SAAW,EAAQkC,SAAW9B,EAAMH,YAE7D,CAMAwC,aAEI,OAAO/Q,KAAK6Q,mBACPnB,QAAQhB,IC4+Cd,SAA0BA,EAAOsC,GACpC,GAAIA,GAAaC,eAAgB,CAC7B,MAAM,eAAEA,EAAc,OAAEC,GAAWF,EACnC,OAAOC,IAAmBvC,EAAMX,IAAMW,EAAMN,OAAS8C,CACzD,CACI,OAAO,CAEf,CDn/CgC,CAAiBxC,KACpCyC,QAAO,CAACC,EAAGC,IAAMD,EAAIC,EAAEpD,MAAM,EACtC,CAOA/G,mBAAmBwH,GACf,OAAIA,EAAMF,UE0SH,KFzSiB8C,iBAAmB5C,EAAML,OAAS,GAI9D,CAMAkD,sBACI,OAAOvR,KAAK8Q,oBAAoBK,QAAO,CAACC,EAAGC,IAAMD,EAAIC,EAAEpD,MAAM,EACjE,CAMAW,qBDtWOf,ECuWe2D,GAAG,QAAQzR,MAAO0R,IAChC,IAAK,MAAMrB,KAAQqB,EAEXzR,KAAKsP,gBAAgB,CAAEvB,GAAIqC,EAAKF,KAAM9B,KAAMgC,EAAKhC,OACjDpO,KAAKgQ,WAAW,CAAEjC,GAAIqC,EAAKF,KAAM9B,KAAMgC,EAAKhC,OAIhDpO,KAAK8P,cE8QN,KF9QiC4B,gBAAgBtB,GACpD,GAER,E,iBGtXQ,IAAIuB,YACJ,IAAIC,Y,kBF+DT,IAAI,EAAO,CAAC,EA6dZ,MAAM,EAAU,IAAI,EAsDpB,SAASC,IAEZ,EAAKC,2BAA2BC,UAAY,gBAG5C,EAAKC,2BAA2BD,UAAY,gBAG5C,EAAKE,2BAA2BF,UAAY,gBAC5C,EAAKG,yBAAyBH,UAAY,iBAI1C,EAAKI,4BAA4BJ,UAAY,gBAC7C,EAAKK,0BAA0BL,UAAY,iBAG3C,EAAKM,8BAA8BN,UAAY,gBAC/C,EAAKO,4BAA4BP,UAAY,gBACjD,CAsCOhS,eAAewS,EAAmBC,EAAUC,GAAQ,GAEvD,MAAMC,QAAe,WAAiB,GAEtC,GAAIA,EAAQ,CAER,MAAMC,GACAF,EAAQ,IAAsB,KAAgB,EAAQC,GAEtD,OAAEE,EAAM,QAAEC,GAzCjB,SAAgCC,GAEnC,IAAIF,EAASE,EAGb,MAAMD,EAAUE,KAAKC,kBAAkB,YAAYvF,SAC/C,iBAEE,CACIZ,MAAO,WACPoG,SAAU,EACVC,gBAAiB,gBAErB,CAAEC,sBAAuB,EAAGC,sBAAuB,GAWzD,MAAO,CAAER,SAAQC,UACrB,CAgBoCQ,CAAuBV,GAGnDH,EAAST,UAAYa,EAAOU,eAAe,QAAST,EACxD,CACJ,CAEO,SAAS,EAAWU,GAAY,GACnC,MAAMC,EAAW,EAAQzC,aAIzB,GAAIwC,EAAW,CAEX,MAAME,GALKD,EAAW,GAKAE,QAAQxS,GACxByS,EAAOF,EAAOtT,OACpB,EAAKyT,cAAc5G,UAAYM,EAC3BmG,EACAE,GAAQ,GAAK,OAAS,QAE1B,EAAKE,mBAAmB7G,UACpBM,EAAemG,GAAU,IAAM,iBAGnC5B,IAGAU,EAAmB,EAAKuB,mBAC5B,CAEA,OAAON,CACX,CAEO,SAAS,EAAkBD,GAAY,GAC1C,MAAMC,EAAW,EAAQjC,sBAGzB,GAAIgC,EAAW,CAEX,MAAME,GAJKD,EAAW,GAIAE,QAAQxS,GACxByS,EAAOF,EAAOtT,OACpB,EAAK4T,qBAAqB/G,UAAYM,EAClCmG,EACAE,GAAQ,GAAK,OAAS,QAE1B,EAAKK,qBAAqBhH,UACtBM,EAAemG,GAAU,IAAM,iBAGnC5B,IAGAU,EAAmB,EAAK0B,oBAAoB,EAChD,CAEA,OAAOT,CACX,CAypEA,SAASU,EAAa5T,GAClB,MAAM8L,EAAU,GAAG,6BNn/EhB,SAAsB+H,GACzB,MAAMC,EAAU7H,SAASC,cAAc,OAEvC,OADA4H,EAAQrC,UAAYoC,EACbC,EAAQpH,SACnB,CM++E8D,CACtD1M,EAAE8L,SAAW9L,EAAE+T,UAEnB,IACI,EAAY,UAAWjI,EAK3B,CAJE,MAAOgD,GAGLpE,MAAMoB,EACV,CACJ,CAl1EyB,oBAw1EzB,IACInB,OAAOoC,iBAAiB,QAAS6G,GACjCjJ,OAAOoC,iBAAiB,qBAAsB6G,EACrC,CAAX,MAAO9E,GAAI,CGn2EN,SAAS,GAAc,QAAEkF,EAAO,UAAE9L,EAAS,OAAE+L,EAAS,YACzD,IAAKD,IAAY9L,EAAW,OAAO,KACnC,MAAMgM,EAAsB,qBAAXD,EAEjB,IAAIE,EAAcjM,Gb7hBKkM,Ea8hBNlM,Eb7hBV,EAAAxK,OAAA,KAAY0W,EAAK,Qa8hBlB,KAA4BJ,EAASE,Gb/hBxC,IAAoBE,EaiiBvB,GAAe,qBAAXH,EAA+B,CAC/B,GAA2B,KAAvBE,EAAYtU,OAEZ,MAAM,IAAI8L,MAAM,8CAEpB,OAAO,EAAWwI,EACtB,CAMA,GAJ2B,KAAvBA,EAAYtU,SACZsU,EAnCR,SAA2BA,GACvB,GAA0B,IAAtBA,EAAYtU,OACZ,MAAM,IAAI8L,MAAM,sDACpB,MAAM0I,EAAIF,EAAYG,MAAM,EAAG,IAI/B,MAAO,CAHGH,EAAYG,MAAM,IAGlB,IAAM,GAAM,EAAI,EAAI,KAAMD,EACxC,CA2BsBE,CAAkBJ,IAGV,IAAtBA,EAAYtU,OACZ,MAAM,IAAI8L,MAAM,sBAGpB,GAAe,mBAAXsI,EACA,OAAO,EAAWE,GAItB,MAAMK,GAAgB,OAAO,IAAIlJ,WAAW6I,IAGtCM,GAAsB,EAAAC,EAAA,GAAUF,GAGhCG,EAAoB,IAAIrJ,WTtjBE,IJO7B,IAAiBsJ,EagjBpBD,EAAkB,GAAK,yBACvB,EAAaA,EAAmBF,EAAqB,GAMrD,MAAMI,GbvjBcD,EaojBYD,GbnjBzB,QAAO,OAAO,IAAIrJ,WAAWsJ,MasjBGN,MAAM,EAAG,GAG1CQ,EAAgB,IAAIxJ,WT/jBDyJ,ISokBzB,OAJA,EAAaD,EAAeH,EAAmB,GAC/C,EAAaG,EAAeD,ETnkBI,ISskBzB,WAAYC,EACvB,C,qDA5N2B,IAAIhK,IAAI,CAE/B,CAAC,MAAO,oCACR,CAAC,MAAO,oCACR,CAAC,MAAO,2CACR,CAAC,MAAO,+CACR,CAAC,MAAO,+CACR,CAAC,MAAO,+CACR,CAAC,MAAO,uCACR,CAAC,MAAO,yCC1XZkK,UAAY,SAAUC,GAClB,OAAa,CACT,MAAMC,EAAW,CAAC,EAClBA,EAASC,KAAO,IAEhBD,EAASE,IAAM,EAAc,CAAEpB,QAASkB,EAASC,OACjDE,YAAYH,EAChB,CACJ,C,iFCVII,EAA2B,CAAC,EAGhC,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,QAAqBzW,IAAjB0W,EACH,OAAOA,EAAaC,QAGrB,IAAIC,EAASL,EAAyBE,GAAY,CACjD/H,GAAI+H,EACJI,QAAQ,EACRF,QAAS,CAAC,GAUX,OANAG,EAAoBL,GAAUM,KAAKH,EAAOD,QAASC,EAAQA,EAAOD,QAASH,GAG3EI,EAAOC,QAAS,EAGTD,EAAOD,OACf,CAGAH,EAAoBQ,EAAIF,EAGxBN,EAAoBlB,EAAI,KAGvB,IAAI2B,EAAsBT,EAAoBU,OAAElX,EAAW,CAAC,IAAI,MAAM,IAAOwW,EAAoB,SAEjG,OADsBA,EAAoBU,EAAED,EAClB,ElBpCvB3Y,EAAW,GACfkY,EAAoBU,EAAI,CAACC,EAAQC,EAAUC,EAAIC,KAC9C,IAAGF,EAAH,CAMA,IAAIG,EAAeC,IACnB,IAAS3K,EAAI,EAAGA,EAAIvO,EAASwC,OAAQ+L,IAAK,CAGzC,IAFA,IAAKuK,EAAUC,EAAIC,GAAYhZ,EAASuO,GACpC4K,GAAY,EACPC,EAAI,EAAGA,EAAIN,EAAStW,OAAQ4W,MACpB,EAAXJ,GAAsBC,GAAgBD,IAAa1W,OAAOC,KAAK2V,EAAoBU,GAAGS,OAAOC,GAASpB,EAAoBU,EAAEU,GAAKR,EAASM,MAC9IN,EAASS,OAAOH,IAAK,IAErBD,GAAY,EACTH,EAAWC,IAAcA,EAAeD,IAG7C,GAAGG,EAAW,CACbnZ,EAASuZ,OAAOhL,IAAK,GACrB,IAAIiL,EAAIT,SACErX,IAAN8X,IAAiBX,EAASW,EAC/B,CACD,CACA,OAAOX,CAnBP,CAJCG,EAAWA,GAAY,EACvB,IAAI,IAAIzK,EAAIvO,EAASwC,OAAQ+L,EAAI,GAAKvO,EAASuO,EAAI,GAAG,GAAKyK,EAAUzK,IAAKvO,EAASuO,GAAKvO,EAASuO,EAAI,GACrGvO,EAASuO,GAAK,CAACuK,EAAUC,EAAIC,EAqBjB,EmBzBdd,EAAoBuB,EAAKnB,IACxB,IAAIoB,EAASpB,GAAUA,EAAOqB,WAC7B,IAAOrB,EAAiB,QACxB,IAAM,EAEP,OADAJ,EAAoB0B,EAAEF,EAAQ,CAAEjG,EAAGiG,IAC5BA,CAAM,ElBNVxZ,EAAWoC,OAAOuX,eAAkBC,GAASxX,OAAOuX,eAAeC,GAASA,GAASA,EAAa,UAQtG5B,EAAoB6B,EAAI,SAASC,EAAOC,GAEvC,GADU,EAAPA,IAAUD,EAAQ3X,KAAK2X,IAChB,EAAPC,EAAU,OAAOD,EACpB,GAAoB,iBAAVA,GAAsBA,EAAO,CACtC,GAAW,EAAPC,GAAaD,EAAML,WAAY,OAAOK,EAC1C,GAAW,GAAPC,GAAoC,mBAAfD,EAAME,KAAqB,OAAOF,CAC5D,CACA,IAAIG,EAAK7X,OAAOuL,OAAO,MACvBqK,EAAoBsB,EAAEW,GACtB,IAAIC,EAAM,CAAC,EACXna,EAAiBA,GAAkB,CAAC,KAAMC,EAAS,CAAC,GAAIA,EAAS,IAAKA,EAASA,IAC/E,IAAI,IAAIK,EAAiB,EAAP0Z,GAAYD,EAAyB,iBAAXzZ,KAAyBN,EAAeoa,QAAQ9Z,GAAUA,EAAUL,EAASK,GACxH+B,OAAOgY,oBAAoB/Z,GAASga,SAASjB,GAASc,EAAId,GAAO,IAAOU,EAAMV,KAI/E,OAFAc,EAAa,QAAI,IAAM,EACvBlC,EAAoB0B,EAAEO,EAAIC,GACnBD,CACR,EmBxBAjC,EAAoB0B,EAAI,CAACvB,EAASmC,KACjC,IAAI,IAAIlB,KAAOkB,EACXtC,EAAoBuC,EAAED,EAAYlB,KAASpB,EAAoBuC,EAAEpC,EAASiB,IAC5EhX,OAAOoY,eAAerC,EAASiB,EAAK,CAAEqB,YAAY,EAAMlQ,IAAK+P,EAAWlB,IAE1E,ECNDpB,EAAoB0C,EAAI,CAAC,EAGzB1C,EAAoBvV,EAAKkY,GACjBtJ,QAAQuJ,IAAIxY,OAAOC,KAAK2V,EAAoB0C,GAAGpH,QAAO,CAACuH,EAAUzB,KACvEpB,EAAoB0C,EAAEtB,GAAKuB,EAASE,GAC7BA,IACL,KCNJ7C,EAAoB8C,EAAKH,GAEjB,KAAOA,EAAU,UCFzB3C,EAAoB+C,SAAYJ,IAEf,ECHjB3C,EAAoBgD,EAAI,WACvB,GAA0B,iBAAfC,WAAyB,OAAOA,WAC3C,IACC,OAAO9Y,MAAQ,IAAI+Y,SAAS,cAAb,EAGhB,CAFE,MAAOzY,GACR,GAAsB,iBAAX2K,OAAqB,OAAOA,MACxC,CACA,CAPuB,GCAxB4K,EAAoBuC,EAAI,CAACX,EAAKuB,IAAU/Y,OAAOgZ,UAAUC,eAAe9C,KAAKqB,EAAKuB,GCClFnD,EAAoBsB,EAAKnB,IACH,oBAAXmD,QAA0BA,OAAOC,aAC1CnZ,OAAOoY,eAAerC,EAASmD,OAAOC,YAAa,CAAEzB,MAAO,WAE7D1X,OAAOoY,eAAerC,EAAS,aAAc,CAAE2B,OAAO,GAAO,ECL9D9B,EAAoBwD,IAAOpD,IAC1BA,EAAOqD,MAAQ,GACVrD,EAAOsD,WAAUtD,EAAOsD,SAAW,IACjCtD,G,MCHR,IAAIuD,EACA3D,EAAoBgD,EAAEY,gBAAeD,EAAY3D,EAAoBgD,EAAE3N,SAAW,IACtF,IAAIqB,EAAWsJ,EAAoBgD,EAAEtM,SACrC,IAAKiN,GAAajN,IACbA,EAASmN,gBACZF,EAAYjN,EAASmN,cAAcC,MAC/BH,GAAW,CACf,IAAII,EAAUrN,EAASsN,qBAAqB,UACzCD,EAAQzZ,SAAQqZ,EAAYI,EAAQA,EAAQzZ,OAAS,GAAGwZ,IAC5D,CAID,IAAKH,EAAW,MAAM,IAAIvN,MAAM,yDAChCuN,EAAYA,EAAUM,QAAQ,OAAQ,IAAIA,QAAQ,QAAS,IAAIA,QAAQ,YAAa,KACpFjE,EAAoBkE,EAAIP,C,WCfxB3D,EAAoBxE,EAAI2I,KAAK9O,SAAW,GAIxC,IAAI+O,EAAkB,CACrB,GAAI,GAgBLpE,EAAoB0C,EAAErM,EAAI,CAACsM,EAASE,KAE/BuB,EAAgBzB,IAElBiB,cAAc5D,EAAoBkE,EAAIlE,EAAoB8C,EAAEH,GAE9D,EAGD,IAAI0B,EAAqBF,KAAsB,gBAAIA,KAAsB,iBAAK,GAC1EG,EAA6BD,EAAmB/J,KAAKiK,KAAKF,GAC9DA,EAAmB/J,KAvBCkK,IACnB,IAAK5D,EAAU6D,EAAaC,GAAWF,EACvC,IAAI,IAAIvE,KAAYwE,EAChBzE,EAAoBuC,EAAEkC,EAAaxE,KACrCD,EAAoBQ,EAAEP,GAAYwE,EAAYxE,IAIhD,IADGyE,GAASA,EAAQ1E,GACdY,EAAStW,QACd8Z,EAAgBxD,EAAS+D,OAAS,EACnCL,EAA2BE,EAAK,C,K3BnB7Bvc,EAAO+X,EAAoBlB,EAC/BkB,EAAoBlB,EAAI,IAChBzF,QAAQuJ,IAAI,CAClB5C,EAAoBvV,EAAE,KACtBuV,EAAoBvV,EAAE,OACpBuX,KAAK/Z,G4BJT,IAAIwY,EAAsBT,EAAoBlB,I","sources":["webpack://MPW/webpack/runtime/chunk loaded","webpack://MPW/webpack/runtime/create fake namespace object","webpack://MPW/webpack/runtime/startup chunk dependencies","webpack://MPW/./scripts/utils.js","webpack://MPW/./scripts/chain_params.js","webpack://MPW/./scripts/prices.js","webpack://MPW/./scripts/settings.js","webpack://MPW/./scripts/misc.js","webpack://MPW/./scripts/script.js","webpack://MPW/./scripts/database.js","webpack://MPW/./scripts/i18n.js","webpack://MPW/./scripts/event_bus.js","webpack://MPW/./scripts/mempool.js","webpack://MPW/./scripts/global.js","webpack://MPW/./scripts/network.js","webpack://MPW/./scripts/aes-gcm.js","webpack://MPW/./scripts/wallet.js","webpack://MPW/./scripts/vanitygen_worker.js","webpack://MPW/webpack/bootstrap","webpack://MPW/webpack/runtime/compat get default export","webpack://MPW/webpack/runtime/define property getters","webpack://MPW/webpack/runtime/ensure chunk","webpack://MPW/webpack/runtime/get javascript chunk filename","webpack://MPW/webpack/runtime/get mini-css chunk filename","webpack://MPW/webpack/runtime/global","webpack://MPW/webpack/runtime/hasOwnProperty shorthand","webpack://MPW/webpack/runtime/make namespace object","webpack://MPW/webpack/runtime/node module decorator","webpack://MPW/webpack/runtime/publicPath","webpack://MPW/webpack/runtime/importScripts chunk loading","webpack://MPW/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var next = __webpack_require__.x;\n__webpack_require__.x = () => {\n\treturn Promise.all([\n\t\t__webpack_require__.e(621),\n\t\t__webpack_require__.e(369)\n\t]).then(next);\n};","import { Buffer } from 'buffer';\nimport { sha256 } from '@noble/hashes/sha256';\n\nexport function hexToBytes(str) {\n return Buffer.from(str, 'hex');\n}\n\nexport function bytesToHex(bytes) {\n return Buffer.from(bytes).toString('hex');\n}\n\n/**\n * Double SHA256 hash a byte array\n * @param {Array} buff - Bytes to hash\n * @returns {Uint8Array} Hash buffer\n */\nexport function dSHA256(buff) {\n return sha256(sha256(new Uint8Array(buff)));\n}\n","// In most BTC-derived coins, the below parameters can be found in the 'src/chainparams.cpp' Mainnet configuration.\n// These below params share the same names as the CPP params, so finding and editing these is easy-peasy!\n// <[network_byte] [32_byte_payload] [0x01] [4_byte_checksum]>\nexport const PRIVKEY_BYTE_LENGTH = 38;\n\nexport const COIN_DECIMALS = 8;\nexport const COIN = 10 ** 8;\n\n/** The maximum gap (absence of transactions within a range of derived addresses) before an account search ends */\nexport const MAX_ACCOUNT_GAP = 20;\n\n/* Internal tweaking parameters */\n// A new encryption password must be 'at least' this long.\nexport const MIN_PASS_LENGTH = 6;\n\n/** BIP21 coin prefix */\nexport const BIP21_PREFIX = 'pivx';\n\n/* chainparams */\nexport const cChainParams = {\n current: null,\n main: {\n name: 'mainnet',\n collateralInSats: 10000 * COIN,\n isTestnet: false,\n TICKER: 'PIV',\n PUBKEY_PREFIX: ['D'],\n STAKING_PREFIX: 'S',\n PUBKEY_ADDRESS: 30,\n SECRET_KEY: 212,\n BIP44_TYPE: 119,\n BIP44_TYPE_LEDGER: 77,\n PROTOCOL_VERSION: 70926,\n MASTERNODE_PORT: 51472,\n // A list of Labs-trusted explorers\n Explorers: [\n // Display name Blockbook-compatible API base\n { name: 'rockdev', url: 'https://explorer.rockdev.org' },\n { name: 'zkBitcoin', url: 'https://zkbitcoin.com' },\n { name: 'Duddino', url: 'https://explorer.duddino.com' },\n ],\n Nodes: [{ name: 'Duddino', url: 'https://rpc.duddino.com/mainnet' }],\n Consensus: {\n // Network upgrades\n UPGRADE_V6_0: undefined,\n },\n budgetCycleBlocks: 43200,\n proposalFee: 50 * COIN,\n maxPaymentCycles: 6,\n maxPayment: 10 * 43200 * COIN, // 43200 blocks of 10 PIV\n },\n testnet: {\n name: 'testnet',\n collateralInSats: 10000 * COIN,\n isTestnet: true,\n TICKER: 'tPIV',\n PUBKEY_PREFIX: ['x', 'y'],\n STAKING_PREFIX: 'W',\n PUBKEY_ADDRESS: 139,\n SECRET_KEY: 239,\n BIP44_TYPE: 1,\n BIP44_TYPE_LEDGER: 1,\n PROTOCOL_VERSION: 70926,\n MASTERNODE_PORT: 51474,\n // A list of Labs-trusted explorers\n Explorers: [\n // Display name Blockbook-compatible API base\n { name: 'rockdev', url: 'https://testnet.rockdev.org' },\n ],\n Nodes: [{ name: 'Duddino', url: 'https://rpc.duddino.com/testnet' }],\n Consensus: {\n // Network upgrades\n UPGRADE_V6_0: undefined,\n },\n budgetCycleBlocks: 144,\n proposalFee: 50 * COIN,\n maxPaymentCycles: 20,\n maxPayment: 10 * 144 * COIN, // 144 blocks of 10 tPIV\n },\n};\n// Set default chain\ncChainParams.current = cChainParams.main;\n","import { getBalance } from './global';\nimport { isEmpty } from './misc';\nimport { cMarket, fillCurrencySelect } from './settings';\n\n/**\n * CoinGecko's endpoint for PIVX data, optimised for least bandwidth\n * - No localisation, tickers, community data, developer data or sparklines\n */\nexport const COINGECKO_ENDPOINT =\n 'https://api.coingecko.com/api/v3/coins/pivx?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false&sparkline=false';\n\n/**\n * The generic market data source template, used to build site-specific classes\n */\nexport class MarketSource {\n /** The storage object for raw market data */\n cData = {};\n\n /** The name of the market source */\n strName = '';\n\n /** The customised API endpoint of the market source */\n strEndpoint = '';\n\n /**\n * Ensure a market data cache exists, if not, fetch it and resume\n */\n async ensureCacheExists() {\n if (!this.cData || !Object.keys(this.cData).length) await this.fetch();\n }\n\n /**\n * Fetches the raw market source data\n * @returns {Promise}\n */\n async fetch() {\n try {\n return (this.cData = await (await fetch(this.strEndpoint)).json());\n } catch (e) {\n console.warn('CoinGecko: Failed to fetch prices!');\n console.warn(e);\n return null;\n }\n }\n}\n\n/**\n * The CoinGecko market data source\n */\nexport class CoinGecko extends MarketSource {\n constructor() {\n super();\n this.strName = 'CoinGecko';\n this.strEndpoint = COINGECKO_ENDPOINT;\n }\n\n /**\n * Get the price in a specific display currency\n * @param {string} strCurrency - The CoinGecko-supported display currency\n * @return {Promise}\n */\n async getPrice(strCurrency) {\n await this.ensureCacheExists();\n return this.cData?.market_data?.current_price[strCurrency] || 0;\n }\n\n /**\n * Get a list of the supported display currencies\n * @returns {Promise>} - A list of CoinGecko-supported display currencies\n */\n async getCurrencies() {\n await this.ensureCacheExists();\n return !isEmpty(this.cData)\n ? Object.keys(this.cData.market_data.current_price)\n : [];\n }\n}\n\n/**\n * Refreshes market data from the user's data source, then re-renders currency options and price displays\n */\nexport async function refreshPriceDisplay() {\n // Refresh our price data, and if successful, update the UI\n if (!isEmpty(await cMarket.fetch())) {\n // Update the currency customisation menu from the selected data source\n await fillCurrencySelect();\n\n // Update price values\n getBalance(true);\n }\n}\n","import {\n doms,\n getBalance,\n getStakingBalance,\n guiUpdateImportInput,\n mempool,\n refreshChainData,\n renderActivityGUI,\n setDisplayForAllWalletOptions,\n updateActivityGUI,\n updateEncryptionGUI,\n updateGovernanceTab,\n} from './global.js';\nimport {\n hasEncryptedWallet,\n importWallet,\n masterKey,\n setMasterKey,\n} from './wallet.js';\nimport { cChainParams } from './chain_params.js';\nimport { setNetwork, ExplorerNetwork, getNetwork } from './network.js';\nimport { confirmPopup, createAlert, isEmpty } from './misc.js';\nimport {\n switchTranslation,\n ALERTS,\n translation,\n arrActiveLangs,\n tr,\n} from './i18n.js';\nimport { CoinGecko, refreshPriceDisplay } from './prices.js';\nimport { Database } from './database.js';\n\n// --- Default Settings\n/** A mode that emits verbose console info for internal MPW operations */\nexport let debug = false;\n/**\n * The user-selected display currency from market-aggregator sites\n * @type {string}\n */\nexport let strCurrency = 'usd';\n/**\n * The global market data source\n * @type {CoinGecko}\n */\nexport let cMarket = new CoinGecko();\n/** The user-selected explorer, used for most of MPW's data synchronisation */\nexport let cExplorer = cChainParams.current.Explorers[0];\n/** The user-selected MPW node, used for alternative blockchain data */\nexport let cNode = cChainParams.current.Nodes[0];\n/** A mode which allows MPW to automatically select it's data sources */\nexport let fAutoSwitch = true;\n/** The active Cold Staking address: default is the PIVX Labs address */\nexport let strColdStakingAddress = 'SdgQDpS8jDRJDX8yK8m9KnTMarsE84zdsy';\n/** The decimals to display for the wallet balance */\nexport let nDisplayDecimals = 2;\n/** A mode which configures MPW towards Advanced users, with low-level feature access and less restrictions (Potentially dangerous) */\nexport let fAdvancedMode = false;\n\nlet transparencyReport;\n\nexport class Settings {\n /**\n * @type {String} analytics level\n */\n analytics;\n /**\n * @type {String} Explorer url to use\n */\n explorer;\n /**\n * @type {String} Node url to use\n */\n node;\n /**\n * @type {Boolean} The Auto-Switch mode state\n */\n autoswitch;\n /**\n * @type {String} The user's active Cold Staking address\n */\n coldAddress;\n /**\n * @type {String} translation to use\n */\n translation;\n /**\n * @type {String} Currency to display\n */\n displayCurrency;\n /**\n * @type {number} The decimals to display for the wallet balance\n */\n displayDecimals;\n /**\n * @type {boolean} Whether Advanced Mode is enabled or disabled\n */\n advancedMode;\n constructor({\n analytics,\n explorer,\n node,\n autoswitch = true,\n coldAddress = strColdStakingAddress,\n translation = '',\n displayCurrency = 'usd',\n displayDecimals = nDisplayDecimals,\n advancedMode = false,\n } = {}) {\n this.analytics = analytics;\n this.explorer = explorer;\n this.node = node;\n this.autoswitch = autoswitch;\n this.coldAddress = coldAddress;\n this.translation = translation;\n this.displayCurrency = displayCurrency;\n this.displayDecimals = displayDecimals;\n this.advancedMode = advancedMode;\n }\n}\n\n// A list of statistic keys and their descriptions\nexport let STATS = {\n // Stat key // Description of the stat, it's data, and it's purpose\n hit: 'A ping indicating an app load, no unique data is sent.',\n time_to_sync: 'The time in seconds it took for MPW to last synchronise.',\n transaction:\n 'A ping indicating a Tx, no unique data is sent, but may be inferred from on-chain time.',\n};\n\nexport const cStatKeys = Object.keys(STATS);\n\n// A list of Analytics 'levels' at which the user may set depending on their privacy preferences\n// NOTE: When changing Level Names, ensure the i18n system is updated to support them too\nlet arrAnalytics = [\n // Statistic level // Allowed statistics\n { name: 'Disabled', stats: [] },\n { name: 'Minimal', stats: [STATS.hit, STATS.time_to_sync] },\n {\n name: 'Balanced',\n stats: [STATS.hit, STATS.time_to_sync, STATS.transaction],\n },\n];\n\nexport let cAnalyticsLevel = arrAnalytics[2];\n\n// Users need not look below here.\n// ------------------------------\n// Global Keystore / Wallet Information\n\n// --- DOM Cache\nexport async function start() {\n //TRANSLATIONS\n //to make translations work we need to change it so that we just enable or disable the visibility of the text\n doms.domTestnet.style.display = cChainParams.current.isTestnet\n ? ''\n : 'none';\n doms.domDebug.style.display = debug ? '' : 'none';\n\n // Hook up the 'currency' select UI\n document.getElementById('currency').onchange = function (evt) {\n setCurrency(evt.target.value);\n };\n\n // Hook up the 'display decimals' slider UI\n doms.domDisplayDecimalsSlider.onchange = function (evt) {\n setDecimals(Number(evt.target.value));\n };\n\n // Hook up the 'explorer' select UI\n document.getElementById('explorer').onchange = function (evt) {\n setExplorer(\n cChainParams.current.Explorers.find(\n (a) => a.url === evt.target.value\n )\n );\n };\n\n // Hook up the 'translation' select UI\n document.getElementById('translation').onchange = function (evt) {\n setTranslation(evt.target.value);\n };\n\n // Hook up the 'analytics' select UI\n document.getElementById('analytics').onchange = function (evt) {\n setAnalytics(arrAnalytics.find((a) => a.name === evt.target.value));\n };\n\n await Promise.all([\n fillExplorerSelect(),\n fillNodeSelect(),\n fillTranslationSelect(),\n ]);\n\n // Fetch price data, then fetch chain data\n if (getNetwork().enabled) {\n refreshPriceDisplay().finally(refreshChainData);\n }\n\n const database = await Database.getInstance();\n\n // Fetch settings from Database\n const {\n analytics: strSettingAnalytics,\n autoswitch,\n coldAddress,\n displayCurrency,\n displayDecimals,\n advancedMode,\n } = await database.getSettings();\n\n // Set the Cold Staking address\n strColdStakingAddress = coldAddress;\n\n // Set any Toggles to their default or DB state\n // Network Auto-Switch\n fAutoSwitch = autoswitch;\n doms.domAutoSwitchToggle.checked = fAutoSwitch;\n\n // Advanced Mode\n fAdvancedMode = advancedMode;\n doms.domAdvancedModeToggler.checked = fAdvancedMode;\n await configureAdvancedMode();\n\n // Set the display currency\n strCurrency = doms.domCurrencySelect.value = displayCurrency;\n\n // Set the display decimals\n nDisplayDecimals = displayDecimals;\n doms.domDisplayDecimalsSlider.value = nDisplayDecimals;\n\n // Apply translations to the transparency report\n STATS = {\n // Stat key // Description of the stat, it's data, and it's purpose\n hit: translation.hit,\n time_to_sync: translation.time_to_sync,\n transaction: translation.transaction,\n };\n transparencyReport = translation.transparencyReport;\n arrAnalytics = [\n // Statistic level // Allowed statistics\n { name: 'Disabled', stats: [] },\n { name: 'Minimal', stats: [STATS.hit, STATS.time_to_sync] },\n {\n name: 'Balanced',\n stats: [STATS.hit, STATS.time_to_sync, STATS.transaction],\n },\n ];\n\n // Initialise status icons as their default variables\n doms.domNetwork.innerHTML =\n '';\n\n // Honour the \"Do Not Track\" header by default\n if (!strSettingAnalytics && navigator.doNotTrack === '1') {\n // Disabled\n setAnalytics(arrAnalytics[0], true);\n doms.domAnalyticsDescriptor.innerHTML =\n '
Analytics disabled to honour \"Do Not Track\" browser setting, you may manually enable if desired, though!
';\n } else {\n // Load from storage, or use defaults\n setAnalytics(\n (cAnalyticsLevel =\n arrAnalytics.find((a) => a.name === strSettingAnalytics) ||\n cAnalyticsLevel),\n true\n );\n }\n\n // Add each analytics level into the UI selector\n fillAnalyticSelect();\n}\n// --- Settings Functions\nexport async function setExplorer(explorer, fSilent = false) {\n const database = await Database.getInstance();\n database.setSettings({ explorer: explorer.url });\n cExplorer = explorer;\n\n // Enable networking + notify if allowed\n const network = new ExplorerNetwork(cExplorer.url, masterKey);\n setNetwork(network);\n\n // Update the selector UI\n doms.domExplorerSelect.value = cExplorer.url;\n\n if (!fSilent)\n createAlert(\n 'success',\n tr(ALERTS.SWITCHED_EXPLORERS, [{ explorerName: cExplorer.name }]),\n 2250\n );\n}\n\nasync function setNode(node, fSilent = false) {\n cNode = node;\n const database = await Database.getInstance();\n database.setSettings({ node: node.url });\n\n // Enable networking + notify if allowed\n getNetwork().enable();\n if (!fSilent)\n createAlert(\n 'success',\n tr(ALERTS.SWITCHED_NODE, [{ node: cNode.name }]),\n 2250\n );\n}\n\n//TRANSLATION\n/**\n * Switches the translation and sets the translation preference to database\n * @param {string} strLang\n */\nexport async function setTranslation(strLang) {\n switchTranslation(strLang);\n const database = await Database.getInstance();\n database.setSettings({ translation: strLang });\n doms.domTranslationSelect.value = strLang;\n}\n\n/**\n * Sets and saves the display currency setting in runtime and database\n * @param {string} currency - The currency string name\n */\nasync function setCurrency(currency) {\n strCurrency = currency;\n const database = await Database.getInstance();\n database.setSettings({ displayCurrency: strCurrency });\n // Update the UI to reflect the new currency\n getBalance(true);\n getStakingBalance(true);\n}\n\n/**\n * Sets and saves the display decimals setting in runtime and database\n * @param {number} decimals - The decimals to set for the display\n */\nasync function setDecimals(decimals) {\n nDisplayDecimals = decimals;\n const database = await Database.getInstance();\n database.setSettings({ displayDecimals: nDisplayDecimals });\n // Update the UI to reflect the new decimals\n getBalance(true);\n getStakingBalance(true);\n}\n\n/**\n * Sets and saves the active Cold Staking address\n * @param {string} strColdAddress - The Cold Staking address\n */\nexport async function setColdStakingAddress(strColdAddress) {\n strColdStakingAddress = strColdAddress;\n const database = await Database.getInstance();\n database.setSettings({ coldAddress: strColdAddress });\n}\n\n/**\n * Fills the translation dropbox on the settings page\n */\nasync function fillTranslationSelect() {\n while (doms.domTranslationSelect.options.length > 0) {\n doms.domTranslationSelect.remove(0);\n }\n\n // Add each language into the UI selector\n for (const cLang of arrActiveLangs) {\n const opt = document.createElement('option');\n opt.innerHTML = `${cLang.emoji} ${cLang.code.toUpperCase()}`;\n opt.value = cLang.code;\n doms.domTranslationSelect.appendChild(opt);\n }\n\n const database = await Database.getInstance();\n const { translation: strLang } = await database.getSettings();\n // And update the UI to reflect them (default to English if none)\n doms.domTranslationSelect.value = strLang;\n}\n\n/**\n * Fills the display currency dropbox on the settings page\n */\nexport async function fillCurrencySelect() {\n const arrCurrencies = await cMarket.getCurrencies();\n\n // Only update if we have a currency list\n if (!isEmpty(arrCurrencies)) {\n while (doms.domCurrencySelect.options.length > 0) {\n doms.domCurrencySelect.remove(0);\n }\n\n // Add each data source currency into the UI selector\n for (const currency of arrCurrencies) {\n const opt = document.createElement('option');\n opt.innerHTML = currency.toUpperCase();\n opt.value = currency;\n doms.domCurrencySelect.appendChild(opt);\n }\n }\n\n const database = await Database.getInstance();\n const { displayCurrency } = await database.getSettings();\n\n // And update the UI to reflect them\n strCurrency = doms.domCurrencySelect.value = displayCurrency;\n}\n\n/**\n * Fills the Analytics Settings UI\n */\nexport function fillAnalyticSelect() {\n const domAnalyticsSelect = document.getElementById('analytics');\n domAnalyticsSelect.innerHTML = '';\n for (const analLevel of arrAnalytics) {\n const opt = document.createElement('option');\n // Apply translation to the display HTML\n opt.value = analLevel.name;\n opt.innerHTML = translation['analytic' + analLevel.name];\n domAnalyticsSelect.appendChild(opt);\n }\n}\n\nasync function setAnalytics(level, fSilent = false) {\n cAnalyticsLevel = level;\n const database = await Database.getInstance();\n await database.setSettings({ analytics: level.name });\n\n // For total transparency, we'll 'describe' the various analytic keys of this chosen level\n let strDesc = '
--- ' + transparencyReport + ' ---

',\n i = 0;\n const nLongestKeyLen = cStatKeys.reduce((prev, e) =>\n prev.length >= e.length ? prev : e\n ).length;\n for (i; i < cAnalyticsLevel.stats.length; i++) {\n const cStat = cAnalyticsLevel.stats[i];\n // This formats Stat keys into { $key $(padding) $description }\n strDesc +=\n cStatKeys\n .find((a) => STATS[a] === cStat)\n .padEnd(nLongestKeyLen, ' ') +\n ': ' +\n cStat +\n '
';\n }\n\n // Set display + notify if allowed\n doms.domAnalyticsDescriptor.innerHTML =\n cAnalyticsLevel.name === arrAnalytics[0].name\n ? ''\n : '
' +\n              strDesc +\n              '
';\n if (!fSilent)\n createAlert(\n 'success',\n tr(ALERTS.SWITCHED_ANALYTICS, [\n { level: translation['analytic' + cAnalyticsLevel.name] },\n ]),\n 2250\n );\n}\n\n/**\n * Toggle between Mainnet and Testnet\n */\nexport async function toggleTestnet() {\n const cNextNetwork = cChainParams.current.isTestnet\n ? cChainParams.main\n : cChainParams.testnet;\n\n // If the current wallet is not saved, we'll ask the user for confirmation, since they'll lose their wallet if they switch with an unsaved wallet!\n if (masterKey && !(await hasEncryptedWallet())) {\n const fContinue = await confirmPopup({\n title: tr(translation.netSwitchUnsavedWarningTitle, [\n { network: cChainParams.current.name },\n ]),\n html: `\n ${tr(translation.netSwitchUnsavedWarningSubtitle, [\n { network: cChainParams.current.name },\n ])}\n
\n ${tr(translation.netSwitchUnsavedWarningSubtext, [\n { network: cNextNetwork.name },\n ])}\n
\n
\n ${\n translation.netSwitchUnsavedWarningConfirmation\n }\n `,\n });\n\n if (!fContinue) {\n // Kick back the \"toggle\" switch\n doms.domTestnetToggler.checked = cChainParams.current.isTestnet;\n return;\n }\n }\n\n // Update current chain config\n cChainParams.current = cNextNetwork;\n\n // Update UI and static tickers\n doms.domTestnet.style.display = cChainParams.current.isTestnet\n ? ''\n : 'none';\n doms.domGuiBalanceTicker.innerText = cChainParams.current.TICKER;\n doms.domGuiBalanceStakingTicker.innerText = cChainParams.current.TICKER;\n doms.domPrefixNetwork.innerText =\n cChainParams.current.PUBKEY_PREFIX.join(' or ');\n\n // Update testnet toggle in settings\n doms.domTestnetToggler.checked = cChainParams.current.isTestnet;\n\n // Check if the new network has an Account\n const cNewDB = await Database.getInstance();\n const cNewAccount = await cNewDB.getAccount();\n if (cNewAccount?.publicKey) {\n // Import the new wallet (overwriting the existing in-memory wallet)\n await importWallet({ newWif: cNewAccount.publicKey });\n } else {\n // Nuke the Master Key\n setMasterKey(null);\n\n // Hide all Dashboard info, kick the user back to the \"Getting Started\" area\n doms.domGenKeyWarning.style.display = 'none';\n doms.domGuiWallet.style.display = 'none';\n doms.domWipeWallet.hidden = true;\n doms.domRestoreWallet.hidden = true;\n\n // Set the \"Wallet Options\" display CSS to it's Default\n setDisplayForAllWalletOptions('');\n\n // Reset the \"Vanity\" and \"Import\" flows\n doms.domPrefix.value = '';\n doms.domPrefix.style.display = 'none';\n\n // Show \"Access Wallet\" button\n doms.domImportWallet.style.display = 'none';\n doms.domPrivKey.style.opacity = '0';\n doms.domAccessWallet.style.display = '';\n doms.domAccessWalletBtn.style.display = '';\n\n // Hide \"Import Wallet\" so the user has to follow the `accessOrImportWallet()` flow\n doms.domImportWallet.style.display = 'none';\n }\n\n // Re-render the Activity UI as empty\n await renderActivityGUI([]);\n\n mempool.UTXOs = [];\n getBalance(true);\n getStakingBalance(true);\n await updateEncryptionGUI(!!masterKey);\n await fillExplorerSelect();\n await fillNodeSelect();\n await updateActivityGUI();\n await updateGovernanceTab();\n}\n\nexport function toggleDebug() {\n debug = !debug;\n doms.domDebug.style.display = debug ? '' : 'none';\n}\n\n/**\n * Toggle the Auto-Switch mode at runtime and in DB\n */\nexport async function toggleAutoSwitch() {\n fAutoSwitch = !fAutoSwitch;\n\n // Update the setting in the DB\n const database = await Database.getInstance();\n await database.setSettings({ autoswitch: fAutoSwitch });\n}\n\nasync function fillExplorerSelect() {\n cExplorer = cChainParams.current.Explorers[0];\n\n while (doms.domExplorerSelect.options.length > 0) {\n doms.domExplorerSelect.remove(0);\n }\n\n // Add each trusted explorer into the UI selector\n for (const explorer of cChainParams.current.Explorers) {\n const opt = document.createElement('option');\n opt.value = explorer.url;\n opt.innerHTML =\n explorer.name + ' (' + explorer.url.replace('https://', '') + ')';\n doms.domExplorerSelect.appendChild(opt);\n }\n\n // Fetch settings from Database\n const database = await Database.getInstance();\n const { explorer: strSettingExplorer } = await database.getSettings();\n\n // For any that exist: load them, or use the defaults\n await setExplorer(\n cChainParams.current.Explorers.find(\n (a) => a.url === strSettingExplorer\n ) || cExplorer,\n true\n );\n\n // And update the UI to reflect them\n doms.domExplorerSelect.value = cExplorer.url;\n}\n\nasync function fillNodeSelect() {\n cNode = cChainParams.current.Nodes[0];\n\n while (doms.domNodeSelect.options.length > 0) {\n doms.domNodeSelect.remove(0);\n }\n\n // Add each trusted node into the UI selector\n for (const node of cChainParams.current.Nodes) {\n const opt = document.createElement('option');\n opt.value = node.url;\n opt.innerHTML =\n node.name + ' (' + node.url.replace('https://', '') + ')';\n doms.domNodeSelect.appendChild(opt);\n }\n\n // Fetch settings from Database\n const database = await Database.getInstance();\n const { node: strSettingNode } = await database.getSettings();\n\n // For any that exist: load them, or use the defaults\n setNode(\n cChainParams.current.Nodes.find((a) => a.url === strSettingNode) ||\n cNode,\n true\n );\n\n // And update the UI to reflect them\n doms.domNodeSelect.value = cNode.url;\n}\n\n/**\n * Toggle Advanced Mode at runtime and in DB\n */\nexport async function toggleAdvancedMode() {\n fAdvancedMode = !fAdvancedMode;\n\n // Configure the app accordingly\n await configureAdvancedMode();\n\n // Update the setting in the DB\n const database = await Database.getInstance();\n await database.setSettings({ advancedMode: fAdvancedMode });\n}\n\n/**\n * Configure the app functionality and UI for the current mode\n */\nasync function configureAdvancedMode() {\n // Re-render the Import Input UI\n await guiUpdateImportInput();\n\n // Hide or Show the \"Mnemonic Passphrase\" in the Seed Creation modal, and reset it's input\n doms.domMnemonicModalPassphrase.value = '';\n doms.domMnemonicModalPassphrase.hidden = !fAdvancedMode;\n}\n","import { translation } from './i18n.js';\nimport { doms } from './global.js';\nimport qrcode from 'qrcode-generator';\nimport bs58 from 'bs58';\nimport { bech32 } from 'bech32';\nimport { BIP21_PREFIX, cChainParams } from './chain_params';\nimport { dSHA256 } from './utils.js';\n\n/* MPW constants */\nexport const pubKeyHashNetworkLen = 21;\nexport const pubChksum = 4;\nexport const pubPrebaseLen = pubKeyHashNetworkLen + pubChksum;\n\n// Base58 Encoding Map\nexport const MAP_B58 =\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nexport const LEN_B58 = MAP_B58.length;\n\n/* --- UTILS --- */\n// Cryptographic Random-Gen\nexport function getSafeRand(nSize = 32) {\n return crypto.getRandomValues(new Uint8Array(nSize));\n}\n\nexport const MAP_ALPHANUMERIC =\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';\n\n/**\n * Generate a random Alpha-Numeric sequence\n * @param {number} nSize - The amount of characters to generate\n * @returns {string} - A random alphanumeric string of nSize length\n */\nexport function getAlphaNumericRand(nSize = 32) {\n let result = '';\n const randValues = getSafeRand(nSize);\n for (const byte of randValues) {\n const index = byte % MAP_ALPHANUMERIC.length;\n result += MAP_ALPHANUMERIC.charAt(index);\n }\n return result;\n}\n\n// Writes a sequence of Array-like bytes into a location within a Uint8Array\nexport function writeToUint8(arr, bytes, pos) {\n const arrLen = arr.length;\n // Sanity: ensure an overflow cannot occur, if one is detected, somewhere in MPW's state could be corrupted.\n if (arrLen - pos - bytes.length < 0) {\n const strERR =\n 'CRITICAL: Overflow detected (' +\n (arrLen - pos - bytes.length) +\n '), possible state corruption, backup and refresh advised.';\n createAlert('warning', strERR, 5000);\n throw Error(strERR);\n }\n let i = 0;\n while (pos < arrLen) arr[pos++] = bytes[i++];\n}\n\n/** Convert a 2D array into a CSV string */\nexport function arrayToCSV(data) {\n return data\n .map(\n (row) =>\n row\n .map(String) // convert every value to String\n .map((v) => v.replaceAll('\"', '\"\"')) // escape double colons\n .map((v) => `\"${v}\"`) // quote it\n .join(',') // comma-separated\n )\n .join('\\r\\n'); // rows starting on new lines\n}\n\n/** Download contents as a file */\nexport function downloadBlob(content, filename, contentType) {\n // Create a blob\n const blob = new Blob([content], { type: contentType });\n\n // Create a link to download it\n const pom = document.createElement('a');\n pom.href = URL.createObjectURL(blob);\n pom.setAttribute('download', filename);\n pom.click();\n}\n\n/**\n * Create a custom GUI Alert popup\n *\n * ### Do NOT display arbitrary / external errors:\n * - The use of `.innerHTML` allows for input styling at this cost.\n * @param {'success'|'info'|'warning'} type - The styling type of the alert\n * @param {string} message - The message to relay to the user\n * @param {number?} timeout - The time in `ms` until the alert expires (Defaults to never expiring)\n */\nexport function createAlert(type, message, timeout = 0) {\n const domAlert = document.createElement('div');\n domAlert.classList.add('notifyWrapper');\n domAlert.classList.add(type);\n setTimeout(() => {\n domAlert.style.opacity = '1';\n domAlert.style.zIndex = '999999';\n domAlert.classList.add('bounce-ani');\n domAlert.classList.add('bounce');\n }, 100);\n\n // Colors for types\n let typeIcon;\n switch (type) {\n case 'warning':\n typeIcon = 'fa-exclamation';\n break;\n case 'info':\n typeIcon = 'fa-info';\n break;\n default:\n // If no valid type is set, default to success\n type == 'success';\n typeIcon = 'fa-check';\n break;\n }\n\n // Message\n domAlert.innerHTML = `\n
\n \n
\n
\n ${message}\n
`;\n domAlert.destroy = () => {\n // Fully destroy timers + DOM elements, no memory leaks!\n clearTimeout(domAlert.timer);\n domAlert.style.opacity = '0';\n setTimeout(() => {\n domAlert.remove();\n }, 600);\n };\n // On Click: Delete alert from DOM after close animation.\n domAlert.addEventListener('click', domAlert.destroy);\n // On Timeout: Delete alert from DOM after a period of inactive time.\n if (timeout > 0) domAlert.timer = setTimeout(domAlert.destroy, timeout);\n doms.domAlertPos.appendChild(domAlert);\n}\n\n/**\n * Shows a Confirm popup with custom HTML.\n *\n * If `resolvePromise` has a value, the popup won't have\n * Confirm/Cancel buttons and will wait for the promise to resolve.\n *\n * Returns the awaited value of `resolvePromise` or `true/false` if the\n * user used a Cancel/Confirm button.\n * @param {object} options\n * @param {string?} options.title - The optional title of the popup\n * @param {string} options.html - The HTML of the popup contents\n * @param {Promise} options.resolvePromise - A promise to resolve before closing the modal\n * @param {boolean?} options.hideConfirm - Whether to hide the Confirm button or not\n * @param {boolean?} options.purpleModal - Toggle a Purple modal, or leave as false for White\n * @param {boolean?} options.textLeft - Toggle to align modal text to the left, or leave as false for center\n * @param {boolean?} options.noPadding - Toggle zero padding, or leave as false for default padding\n * @param {number?} options.maxHeight - An optional modal Max Height, omit for default modal max\n * @returns {Promise}\n */\nexport async function confirmPopup({\n title,\n html,\n resolvePromise,\n hideConfirm,\n purpleModal,\n textLeft,\n noPadding,\n maxHeight,\n}) {\n // If there's a title provided: display the header and text\n doms.domConfirmModalHeader.style.display = title ? 'block' : 'none';\n doms.domConfirmModalTitle.innerHTML = title || '';\n\n // If there's a promise to resolve, don't display buttons; the modal visibility will be controlled by the promise (f.e: a 'pls wait' screen)\n doms.domConfirmModalButtons.style.setProperty(\n 'display',\n resolvePromise ? 'none' : 'block',\n resolvePromise ? 'important' : undefined\n );\n $('#confirmModal').modal(resolvePromise ? 'show' : { keyboard: false });\n\n // Show or hide the confirm button, and replace 'Cancel' with 'Close'\n doms.domConfirmModalConfirmButton.style.display = hideConfirm ? 'none' : '';\n doms.domConfirmModalCancelButton.innerText = hideConfirm\n ? translation.popupClose\n : translation.popupCancel;\n\n // Set content display\n doms.domConfirmModalContent.innerHTML = html;\n\n // Set text align to left\n if (textLeft) {\n doms.domConfirmModalContent.classList.remove('center-text');\n } else {\n doms.domConfirmModalContent.classList.add('center-text');\n }\n\n // Use the purple modal\n if (purpleModal) {\n doms.domConfirmModalMain.classList.add('exportKeysModalColor');\n } else {\n doms.domConfirmModalMain.classList.remove('exportKeysModalColor');\n }\n\n // Remove padding\n if (noPadding) {\n doms.domConfirmModalContent.classList.add('px-0');\n doms.domConfirmModalContent.classList.add('pb-0');\n } else {\n doms.domConfirmModalContent.classList.remove('px-0');\n doms.domConfirmModalContent.classList.remove('pb-0');\n }\n\n // Set max-height (removed at `.finally` context)\n if (maxHeight)\n doms.domConfirmModalDialog.classList.add(`max-w-${maxHeight}`);\n\n // If there's an input in the prompt, focus the cursor upon it\n for (const domElement of doms.domConfirmModalContent.children) {\n if (domElement.type === 'text' || domElement.type === 'password') {\n domElement.focus();\n break;\n }\n }\n\n // Wait for the promise to resolve OR create a new one which resolves upon a modal button click\n resolvePromise =\n resolvePromise ||\n new Promise((res, _) => {\n doms.domConfirmModalConfirmButton.onclick = () => {\n res(true);\n };\n doms.domConfirmModalCancelButton.onclick = () => {\n res(false);\n };\n });\n try {\n return await resolvePromise;\n } finally {\n // We want to hide the modal even if an exception occurs\n $('#confirmModal').modal('hide');\n\n // Reset any modal settings\n doms.domConfirmModalDialog.classList.remove(`max-w-${maxHeight}`);\n }\n}\n\n// Generates and sets a QRCode image from a string and dom element\nexport function createQR(strData = '', domImg, size = 4) {\n // QRCode class consists of 'typeNumber' & 'errorCorrectionLevel'\n const cQR = qrcode(size, 'L');\n cQR.addData(strData);\n cQR.make();\n domImg.innerHTML = cQR.createImgTag(2, 2);\n domImg.firstChild.style.borderRadius = '8px';\n}\n\n/**\n * Prompt image selection, and return base64 of an image file.\n * @returns {Promise} The base64 string of the selected image file.\n */\nexport async function getImageFile() {\n return new Promise((resolve) => {\n let input = document.createElement('input');\n input.type = 'file';\n input.accept = 'image/*';\n input.onchange = (e) => {\n let file = e.target.files[0];\n let reader = new FileReader();\n reader.onloadend = () => resolve(reader.result);\n reader.readAsDataURL(file);\n };\n input.click();\n });\n}\n\n/**\n * A quick check to see if an address is a Standard (P2PKH) address\n * @param {string} strAddress - The address to check\n * @returns {boolean} - `true` if a Standard address, `false` if not\n */\nexport function isStandardAddress(strAddress) {\n return (\n strAddress.length === 34 &&\n cChainParams.current.PUBKEY_PREFIX.includes(strAddress[0])\n );\n}\n\n/**\n * A quick check to see if a string is an XPub key\n * @param {string} strXPub - The XPub to check\n * @returns {boolean} - `true` if a valid formatted XPub, `false` if not\n */\nexport function isXPub(strXPub) {\n if (!strXPub.startsWith('xpub')) return false;\n\n // Attempt to Base58 decode the XPub\n try {\n // Slice away the `xpub` prefix and decode\n const decoded = bs58.decode(strXPub.slice(4));\n\n // Then verify the final length too\n return decoded.length === 78;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Attempt to safely parse a BIP21 Payment Request\n * @param {string} strReq - BIP21 Payment Request string\n * @returns {object | false}\n */\nexport function parseBIP21Request(strReq) {\n // Format should match: pivx:addr[?amount=x&label=x]\n if (!strReq.includes(BIP21_PREFIX + ':')) return false;\n\n const [addressPart, optionsPart] = strReq.includes('?')\n ? strReq.split('?')\n : [strReq, false];\n const strAddress = addressPart.substring(BIP21_PREFIX.length + 1); // remove 'pivx:' prefix\n let cOptions = {};\n\n // Ensure the address is valid\n if (\n // Standard address\n !isStandardAddress(strAddress) &&\n // Shield address\n !isValidBech32(strAddress).valid\n ) {\n return false;\n }\n\n if (optionsPart) {\n cOptions = Object.fromEntries(\n optionsPart\n .split('&')\n .map((opt) => opt.split('=').map(decodeURIComponent))\n );\n }\n\n return { address: strAddress, options: cOptions };\n}\n\n/**\n * @typedef {object} Bech32Check\n * @property {boolean} valid - If the string is a valid bech32 address\n * @property {object} res - The results of the bech32 decoding\n */\n\n/**\n * A safe bech32 wrapper for quickly checking if an address is valid\n * @param {string} str - Bech32 Address\n * @returns {Bech32Check} - Both the validity and decoding results\n */\nexport function isValidBech32(str) {\n try {\n return { valid: true, res: bech32.decode(str) };\n } catch (e) {\n return { valid: false, res: e };\n }\n}\n\n/**\n * Generate an encoded private key for masternodes\n */\nexport function generateMasternodePrivkey() {\n // Prefix the network byte with the private key (32 random bytes)\n const data = [cChainParams.current.SECRET_KEY, ...getSafeRand(32)];\n\n // Compute and concatenate the checksum, then encode the private key as Base58\n return bs58.encode([...data, ...dSHA256(data).slice(0, 4)]);\n}\n\nexport function sanitizeHTML(text) {\n const element = document.createElement('div');\n element.innerText = text;\n return element.innerHTML;\n}\n\n/**\n * \"Beautifies\" a number with HTML, by displaying decimals in a lower opacity\n * @param {string} strNumber - The number in String form to beautify\n * @param {string?} strDecFontSize - The optional font size to display decimals in\n * @returns {string} - A HTML string with beautified number handling\n */\nexport function beautifyNumber(strNumber, strDecFontSize = '') {\n if (typeof strNumber === 'number') strNumber = strNumber.toString();\n\n // Only run this for numbers with decimals\n if (!strNumber.includes('.')) return strNumber;\n\n // Split the number in to Full and Decimal parts\n const arrNumParts = strNumber.split('.');\n\n // Return a HTML that renders the decimal in a lower opacity\n const strFontSize = strDecFontSize ? 'font-size: ' + strDecFontSize : '';\n return `${arrNumParts[0]}.${arrNumParts[1]}`;\n}\n\n/**\n * Check if a string is valid Base64 encoding\n * @param {string} str - String to check\n * @returns {boolean}\n */\nexport function isBase64(str) {\n const base64Regex = /^[A-Za-z0-9+/=]+$/;\n\n // Check if the string contains only Base64 characters:\n if (!base64Regex.test(str)) {\n return false;\n }\n\n // Check if the length is a multiple of 4 (required for Base64):\n if (str.length % 4 !== 0) {\n return false;\n }\n\n // Try decoding the Base64 string to check for errors:\n try {\n atob(str);\n } catch (e) {\n return false;\n }\n\n // The string is likely Base64-encoded:\n return true;\n}\n\n/**\n * Checks if two values are of the same type.\n *\n * @param {any} a - The first value.\n * @param {any} b - The second value.\n * @returns {boolean} - `true` if the values are of the same type, `false` if not or if there was an error comparing.\n */\nexport function isSameType(a, b) {\n try {\n if (a === null || b === null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a === 'object')\n return Object.getPrototypeOf(a) === Object.getPrototypeOf(b);\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Checks if a value is 'empty'.\n *\n * @param {any} val - The value to check.\n * @returns {boolean} - `true` if the value is 'empty', `false` otherwise.\n * ---\n * Values **considered 'empty'**: `null`, `undefined`, empty strings, empty arrays, empty objects.\n *\n * Values **NOT considered 'empty'**: Any non-nullish primitive value: numbers (including `0` and `NaN`), `true`, `false`, `Symbol()`, `BigInt()`.\n */\nexport function isEmpty(val) {\n return (\n val == null ||\n val === '' ||\n (Array.isArray(val) && val.length === 0) ||\n (typeof val === 'object' && Object.keys(val).length === 0)\n );\n}\n\n/**\n * An artificial sleep function to pause code execution\n *\n * @param {Number} ms - The milliseconds to sleep\n *\n * @example\n * // Pause an asynchronous script for 1 second\n * await sleep(1000);\n */\nexport function sleep(ms) {\n return new Promise((res, _) => setTimeout(res, ms));\n}\n","export const OP = {\n // push value\n 0: 0x00,\n FALSE: 0x00, // ALIAS FOR: 0\n PUSHDATA1: 0x4c,\n PUSHDATA2: 0x4d,\n PUSHDATA4: 0x4e,\n '1NEGATE': 0x4f,\n RESERVED: 0x50,\n 1: 0x51,\n TRUE: 0x51, // ALIAS FOR: 1\n 2: 0x52,\n 3: 0x53,\n 4: 0x54,\n 5: 0x55,\n 6: 0x56,\n 7: 0x57,\n 8: 0x58,\n 9: 0x59,\n 10: 0x5a,\n 11: 0x5b,\n 12: 0x5c,\n 13: 0x5d,\n 14: 0x5e,\n 15: 0x5f,\n 16: 0x60,\n\n // control\n NOP: 0x61,\n VER: 0x62,\n IF: 0x63,\n NOTIF: 0x64,\n VERIF: 0x65,\n VERNOTIF: 0x66,\n ELSE: 0x67,\n ENDIF: 0x68,\n VERIFY: 0x69,\n RETURN: 0x6a,\n\n // stack ops\n TOALTSTACK: 0x6b,\n FROMALTSTACK: 0x6c,\n '2DROP': 0x6d,\n '2DUP': 0x6e,\n '3DUP': 0x6f,\n '2OVER': 0x70,\n '2ROT': 0x71,\n '2SWAP': 0x72,\n IFDUP: 0x73,\n DEPTH: 0x74,\n DROP: 0x75,\n DUP: 0x76,\n NIP: 0x77,\n OVER: 0x78,\n PICK: 0x79,\n ROLL: 0x7a,\n ROT: 0x7b,\n SWAP: 0x7c,\n TUCK: 0x7d,\n\n // splice ops\n CAT: 0x7e,\n SUBSTR: 0x7f,\n LEFT: 0x80,\n RIGHT: 0x81,\n SIZE: 0x82,\n\n // bit logic\n INVERT: 0x83,\n AND: 0x84,\n OR: 0x85,\n XOR: 0x86,\n EQUAL: 0x87,\n EQUALVERIFY: 0x88,\n RESERVED1: 0x89,\n RESERVED2: 0x8a,\n\n // numeric\n '1ADD': 0x8b,\n '1SUB': 0x8c,\n '2MUL': 0x8d,\n '2DIV': 0x8e,\n NEGATE: 0x8f,\n ABS: 0x90,\n NOT: 0x91,\n '0NOTEQUAL': 0x92,\n\n ADD: 0x93,\n SUB: 0x94,\n MUL: 0x95,\n DIV: 0x96,\n MOD: 0x97,\n LSHIFT: 0x98,\n RSHIFT: 0x99,\n\n BOOLAND: 0x9a,\n BOOLOR: 0x9b,\n NUMEQUAL: 0x9c,\n NUMEQUALVERIFY: 0x9d,\n NUMNOTEQUAL: 0x9e,\n LESSTHAN: 0x9f,\n GREATERTHAN: 0xa0,\n LESSTHANOREQUAL: 0xa1,\n GREATERTHANOREQUAL: 0xa2,\n MIN: 0xa3,\n MAX: 0xa4,\n\n WITHIN: 0xa5,\n\n // crypto\n RIPEMD160: 0xa6,\n SHA1: 0xa7,\n SHA256: 0xa8,\n HASH160: 0xa9,\n HASH256: 0xaa,\n CODESEPARATOR: 0xab,\n CHECKSIG: 0xac,\n CHECKSIGVERIFY: 0xad,\n CHECKMULTISIG: 0xae,\n CHECKMULTISIGVERIFY: 0xaf,\n\n // expansion\n NOP1: 0xb0,\n NOP2: 0xb1,\n CHECKLOCKTIMEVERIFY: 0xb1, // ALIAS FOR: NOP2\n NOP3: 0xb2,\n NOP4: 0xb3,\n NOP5: 0xb4,\n NOP6: 0xb5,\n NOP7: 0xb6,\n NOP8: 0xb7,\n NOP9: 0xb8,\n NOP10: 0xb9,\n\n // zerocoin\n ZEROCOINMINT: 0xc1,\n ZEROCOINSPEND: 0xc2,\n ZEROCOINPUBLICSPEND: 0xc3,\n\n // cold staking\n CHECKCOLDSTAKEVERIFY_LOF: 0xd1, // last output free for masternode/budget payments\n CHECKCOLDSTAKEVERIFY: 0xd2,\n\n INVALIDOPCODE: 0xff,\n};\nObject.freeze(OP);\n\nexport function getScriptForBurn(data) {\n let cScript = [];\n // Check if we're fitting any data into the TX\n if (typeof data === 'string' && data.length > 0) {\n let bData = new TextEncoder().encode(data);\n cScript.push(OP['RETURN']);\n cScript.push(OP['PUSHDATA1']);\n // Append the byte array length\n cScript.push(bData.length);\n // Convert from uint8 to array and append the byte array\n cScript = cScript.concat(Array.prototype.slice.call(bData));\n } else {\n // Empty data, create a simple RETURN script\n cScript.push(OP['RETURN']);\n }\n // Return the burn script\n return cScript;\n}\n","import { openDB, IDBPDatabase } from 'idb';\nimport Masternode from './masternode.js';\nimport { Settings } from './settings.js';\nimport { cChainParams } from './chain_params.js';\nimport {\n confirmPopup,\n sanitizeHTML,\n createAlert,\n isSameType,\n isEmpty,\n} from './misc.js';\nimport { PromoWallet } from './promos.js';\nimport { ALERTS, translation } from './i18n.js';\nimport { Account } from './accounts.js';\n\n/** The current version of the DB - increasing this will prompt the Upgrade process for clients with an older version */\nexport const DB_VERSION = 2;\n\n/**\n *\n */\nexport class Database {\n /**\n * Current Database Version.\n * Version 1 = Add index DB (PR #[FILL])\n * @type{Number}\n */\n static version = 1;\n\n /**\n * @type{IDBPDatabase}\n */\n #db;\n\n constructor({ db }) {\n this.#db = db;\n }\n\n close() {\n this.#db.close();\n this.#db = null;\n }\n\n /**\n * Add masternode to the database\n * @param {Masternode} masternode\n * @param {Masterkey} _masterKey - Masterkey associated to the masternode. Currently unused\n */\n async addMasternode(masternode, _masterKey) {\n const store = this.#db\n .transaction('masternodes', 'readwrite')\n .objectStore('masternodes');\n // For now the key is 'masternode' since we don't support multiple masternodes\n await store.put(masternode, 'masternode');\n }\n /**\n * Removes a masternode\n * @param {Masterkey} _masterKey - Masterkey associated to the masternode. Currently unused\n */\n async removeMasternode(_masterKey) {\n const store = this.#db\n .transaction('masternodes', 'readwrite')\n .objectStore('masternodes');\n await store.delete('masternode');\n }\n\n /**\n * Add Promo Code to the database for tracking and management\n * @param {PromoWallet} promo\n */\n async addPromo(promo) {\n const store = this.#db\n .transaction('promos', 'readwrite')\n .objectStore('promos');\n // The plaintext code is our key, since codes are unique and deterministic anyway\n await store.put(promo, promo.code);\n }\n /**\n * Removes a Promo Code from the Promo management system\n * @param {string} promo - the promo code to remove\n */\n async removePromo(promo) {\n const store = this.#db\n .transaction('promos', 'readwrite')\n .objectStore('promos');\n await store.delete(promo);\n }\n\n /**\n * Adds an account to the database\n *\n * This will also apply missing Account keys from the Account class automatically, and check high-level type safety.\n * @param {Account} account - The Account to add\n */\n async addAccount(account) {\n // Critical: Ensure the input is an Account instance\n if (!(account instanceof Account)) {\n console.error(\n '---- addAccount() called with invalid input, input dump below ----'\n );\n console.error(account);\n console.error('---- end of account dump ----');\n createAlert(\n 'warning',\n 'Account Creation Error
Logs were dumped in your Browser Console
Please submit these privately to PIVX Labs Developers!'\n );\n return false;\n }\n\n // Create an empty DB Account\n const cDBAccount = new Account();\n\n // We'll overlay the `account` keys atop the `DB Account` keys:\n // Note: Since the Account constructor defaults all properties to type-safe defaults, we can already assume `cDBAccount` is safe.\n // Note: Since `addAccount` could be called with *anything*, we must apply the same type-safety on it's input.\n for (const strKey of Object.keys(cDBAccount)) {\n // Ensure the Type is correct for the Key against the Account class\n if (!isSameType(account[strKey], cDBAccount[strKey])) {\n console.error(\n 'DB: addAccount() key \"' +\n strKey +\n '\" does NOT match the correct class type, likely data mismatch, please report!'\n );\n continue;\n }\n\n // Overlay the 'new' keys on top of the DB keys\n cDBAccount[strKey] = account[strKey];\n }\n\n const store = this.#db\n .transaction('accounts', 'readwrite')\n .objectStore('accounts');\n\n // Check this account isn't already added (by pubkey once multi-account)\n if (await store.get('account'))\n return console.error(\n 'DB: Ran addAccount() when account already exists!'\n );\n\n // When the account system is going to be added, the key is gonna be the publicKey\n await store.put(cDBAccount, 'account');\n }\n\n /**\n * Update specified keys for an Account in the DB.\n *\n * This will also apply new Account keys from MPW updates automatically, and check high-level type safety.\n *\n * ---\n *\n * To allow \"deleting/clearing/resetting\" keys, for example, when removing Proposals or Contacts, toggle `allowDeletion`.\n *\n * **Do NOT toggle unless otherwise necessary**, to avoid overwriting keys from code errors or misuse.\n * @param {Account} account - The Account to update, with new data inside\n * @param {boolean} allowDeletion - Allow setting keys to an \"empty\" state (`\"\"`, `[]`, `{}`)\n */\n async updateAccount(account, allowDeletion = false) {\n // Critical: Ensure the input is an Account instance\n if (!(account instanceof Account)) {\n console.error(\n '---- updateAccount() called with invalid input, input dump below ----'\n );\n console.error(account);\n console.error('---- end of account dump ----');\n createAlert(\n 'warning',\n 'DB Update Error
Your wallet is safe, logs were dumped in your Browser Console
Please submit these privately to PIVX Labs Developers!'\n );\n return false;\n }\n\n // Fetch the DB account\n const cDBAccount = await this.getAccount();\n\n // If none exists; we should throw an error, as there's no reason for MPW to call `updateAccount` before an account was added using `addAccount`\n // Note: This is mainly to force \"good standards\" in which we don't lazily use `updateAccount` to create NEW accounts.\n if (!cDBAccount) {\n console.error(\n '---- updateAccount() called without an account existing, input dump below ----'\n );\n console.error(account);\n console.error('---- end of input dump ----');\n createAlert(\n 'warning',\n 'DB Update Error
Logs were dumped in your Browser Console
Please submit these privately to PIVX Labs Developers!'\n );\n return false;\n }\n\n // We'll overlay the `account` keys atop the `DB Account` keys:\n // Note: Since `getAccount` already checks type-safety, we can already assume `cDBAccount` is safe.\n // Note: Since `updateAccount` could be called with *anything*, we must apply the same type-safety on it's input.\n for (const strKey of Object.keys(cDBAccount)) {\n // Ensure the Type is correct for the Key against the Account class\n if (!isSameType(account[strKey], cDBAccount[strKey])) {\n console.error(\n 'DB: updateAccount() key \"' +\n strKey +\n '\" does NOT match the correct class type, likely data mismatch, please report!'\n );\n continue;\n }\n\n // Ensure the 'updated' key (which may not exist) is NOT a default or EMPTY value\n // Note: this can be overriden manually when erasing data such as Contacts, Local Proposals, etc.\n if (!allowDeletion && isEmpty(account[strKey])) continue;\n\n // Overlay the 'new' keys on top of the DB keys\n cDBAccount[strKey] = account[strKey];\n }\n\n const store = this.#db\n .transaction('accounts', 'readwrite')\n .objectStore('accounts');\n // When the account system is going to be added, the key is gonna be the publicKey\n await store.put(cDBAccount, 'account');\n }\n\n /**\n * Removes an account from the database\n * @param {Object} o\n * @param {String} o.publicKey - Public key associated to the account.\n */\n async removeAccount({ publicKey }) {\n const store = this.#db\n .transaction('accounts', 'readwrite')\n .objectStore('accounts');\n // When the account system is going to be added, the key is gonna be the publicKey\n await store.delete('account');\n }\n\n /**\n * Gets an account from the database.\n *\n * This also will apply new keys from MPW updates automatically, and check high-level type safety.\n * @returns {Promise}\n */\n async getAccount() {\n const store = this.#db\n .transaction('accounts', 'readonly')\n .objectStore('accounts');\n const cDBAccount = await store.get('account');\n\n // If there's no DB Account, we'll return null early\n if (!cDBAccount) return null;\n\n // We'll generate an Account Class for up-to-date keys, then layer the 'new' type-checked properties on it one-by-one\n const cAccount = new Account();\n for (const strKey of Object.keys(cAccount)) {\n // Ensure the Type is correct for the Key against the Account class (with instanceof to also check Class validity)\n if (!isSameType(cDBAccount[strKey], cAccount[strKey])) {\n console.error(\n 'DB: getAccount() key \"' +\n strKey +\n '\" does NOT match the correct class type, likely bad data saved, please report!'\n );\n continue;\n }\n\n // Overlay the 'DB' keys on top of the Class Instance keys\n cAccount[strKey] = cDBAccount[strKey];\n }\n\n // Return the Account Class\n return cAccount;\n }\n\n /**\n * @returns {Promise} the masternode stored in the db\n */\n async getMasternode(_masterKey) {\n const store = this.#db\n .transaction('masternodes', 'readonly')\n .objectStore('masternodes');\n return new Masternode(await store.get('masternode'));\n }\n\n /**\n * @returns {Promise>} all Promo Codes stored in the db\n */\n async getAllPromos() {\n const store = this.#db\n .transaction('promos', 'readonly')\n .objectStore('promos');\n // Convert all promo objects in to their Class and return them as a new array\n return (await store.getAll()).map((promo) => new PromoWallet(promo));\n }\n\n /**\n * @returns {Promise}\n */\n async getSettings() {\n const store = this.#db\n .transaction('settings', 'readonly')\n .objectStore('settings');\n return new Settings(await store.get('settings'));\n }\n\n /**\n * @param {Settings} settings - settings to use\n * @returns {Promise}\n */\n async setSettings(settings) {\n const oldSettings = await this.getSettings();\n const store = this.#db\n .transaction('settings', 'readwrite')\n .objectStore('settings');\n await store.put(\n {\n ...oldSettings,\n ...settings,\n },\n 'settings'\n );\n }\n\n /**\n * Migrates from local storage\n * @param {IDBPDatabase} db\n */\n async #migrateLocalStorage() {\n if (localStorage.length === 0) return;\n const settings = new Settings({\n analytics: localStorage.analytics,\n explorer: localStorage.explorer,\n node: localStorage.node,\n translation: localStorage.translation,\n displayCurrency: localStorage.displayCurrency,\n });\n await this.setSettings(settings);\n\n if (localStorage.masternode) {\n try {\n const masternode = JSON.parse(localStorage.masternode);\n await this.addMasternode(masternode);\n } catch (e) {\n console.error(e);\n createAlert('warning', ALERTS.MIGRATION_MASTERNODE_FAILURE);\n }\n }\n\n if (localStorage.encwif || localStorage.publicKey) {\n try {\n const localProposals = JSON.parse(\n localStorage.localProposals || '[]'\n );\n\n // Update and format the old Account data\n const cAccount = new Account({\n publicKey: localStorage.publicKey,\n encWif: localStorage.encwif,\n localProposals: localProposals,\n });\n\n // Migrate the old Account data to the new DB\n await this.addAccount(cAccount);\n } catch (e) {\n console.error(e);\n createAlert('warning', ALERTS.MIGRATION_ACCOUNT_FAILURE);\n if (localStorage.encwif) {\n await confirmPopup({\n title: translation.MIGRATION_ACCOUNT_FAILURE_TITLE,\n html: `${\n translation.MIGRATION_ACCOUNT_FAILURE_HTML\n } ${sanitizeHTML(\n localStorage.encwif\n )} `,\n });\n }\n }\n }\n }\n\n static async create(name) {\n let migrate = false;\n const database = new Database({ db: null });\n const db = await openDB(`MPW-${name}`, DB_VERSION, {\n upgrade: (db, oldVersion) => {\n console.log(\n 'DB: Upgrading from ' + oldVersion + ' to ' + DB_VERSION\n );\n if (oldVersion == 0) {\n db.createObjectStore('masternodes');\n db.createObjectStore('accounts');\n db.createObjectStore('settings');\n migrate = true;\n }\n\n // The introduction of PIVXPromos (safely added during {\n // Another instance is waiting to upgrade, and we're preventing it\n // Close the database and refresh the page\n // (This would only happen if the user opened another window after MPW got an update)\n database.close();\n alert('New update received!');\n window.location.reload();\n },\n });\n database.#db = db;\n if (migrate) {\n database.#migrateLocalStorage();\n }\n return database;\n }\n\n /**\n * Map name->instnace\n * @type{Map}\n */\n static #instances = new Map();\n\n /**\n * @return {Promise} the default database instance\n */\n static async getInstance() {\n const name = cChainParams.current.name;\n const instance = this.#instances.get(name);\n if (!instance || !instance.#db) {\n this.#instances.set(name, await Database.create(name));\n }\n\n return this.#instances.get(name);\n }\n}\n","import { en_translation } from '../locale/en/translation.js';\nimport { pt_br_translation } from '../locale/pt-br/translation.js';\nimport { pt_pt_translation } from '../locale/pt-pt/translation.js';\nimport { ph_translation } from '../locale/ph/translation.js';\nimport { uwu_translation } from '../locale/uwu/translation.js';\nimport { fr_translation } from '../locale/fr/translation.js';\nimport { de_translation } from '../locale/de/translation.js';\nimport { Database } from './database.js';\nimport { fillAnalyticSelect, setTranslation } from './settings.js';\nimport { renderActivityGUI, updateEncryptionGUI } from './global.js';\nimport { masterKey } from './wallet.js';\nimport { getNetwork } from './network.js';\nimport { cReceiveType, guiToggleReceiveType } from './contacts-book.js';\n\nexport const ALERTS = {};\nexport let translation = {};\n\n// TRANSLATION\n//Create an object of objects filled with all the translations\nexport const translatableLanguages = {\n en: en_translation,\n uwu: uwu_translation,\n 'pt-pt': pt_pt_translation,\n 'pt-br': pt_br_translation,\n ph: ph_translation,\n fr: fr_translation,\n de: de_translation,\n};\n\n/**\n * Takes the language name and sets the translation settings based on the language file\n * @param {string} langName\n */\nexport function switchTranslation(langName) {\n if (arrActiveLangs.find((lang) => lang.code === langName)) {\n // Load every 'active' key of the language, otherwise, we'll default the key to the EN file\n const arrNewLang = translatableLanguages[langName];\n for (const strKey of Object.keys(arrNewLang)) {\n // Skip empty and/or missing i18n keys, defaulting them to EN\n if (!arrNewLang[strKey]) {\n translation[strKey] = translatableLanguages.en[strKey];\n continue;\n }\n\n // Apply the new i18n value to our runtime i18n sheet\n translation[strKey] = arrNewLang[strKey];\n }\n\n // Translate static`data-i18n` tags\n translateStaticHTML(translation);\n\n // Translate any dynamic elements necessary\n const cNet = getNetwork();\n if (masterKey && cNet) {\n updateEncryptionGUI();\n renderActivityGUI(cNet.arrTxHistory);\n }\n loadAlerts();\n fillAnalyticSelect();\n if (masterKey) {\n guiToggleReceiveType(cReceiveType);\n }\n return true;\n } else {\n console.log(\n 'i18n: The language (' +\n langName +\n \") is not supported yet, if you'd like to contribute translations (for rewards!) contact us on GitHub or Discord!\"\n );\n translation = translatableLanguages.en_translation;\n return false;\n }\n}\n\n/**\n * Takes an i18n string that includes `{x}` and replaces that based on what is in the array of objects\n * @param {string} message\n * @param {Array} variables\n * @returns a string with the variables implemented in the string\n *\n * @example\n * //returns \"test this\"\n * tr(\"test {x}\" [x: \"this\"])\n */\nexport function tr(message, variables) {\n variables.forEach((element) => {\n message = message.replaceAll(\n '{' + Object.keys(element)[0] + '}',\n Object.values(element)[0]\n );\n });\n return message;\n}\n\n/**\n * Translates all static HTML based on the `data-i18n` tag\n * @param {Array} i18nLangs\n *\n */\nexport function translateStaticHTML(i18nLangs) {\n if (!i18nLangs) return;\n\n document.querySelectorAll('[data-i18n]').forEach(function (element) {\n if (!i18nLangs[element.dataset.i18n]) return;\n\n if (element.dataset.i18n_target) {\n element[element.dataset.i18n_target] =\n i18nLangs[element.dataset.i18n];\n } else {\n switch (element.tagName.toLowerCase()) {\n case 'input':\n case 'textarea':\n element.placeholder = i18nLangs[element.dataset.i18n];\n break;\n default:\n element.innerHTML = i18nLangs[element.dataset.i18n];\n break;\n }\n }\n });\n loadAlerts();\n}\n\n/**\n * Translates the alerts by loading the data into the ALERTS object\n */\nexport function loadAlerts() {\n // Alerts are designated by a special 'ALERTS' entry in each translation file\n let fFoundAlerts = false;\n for (const [alert_key, alert_translation] of Object.entries(translation)) {\n if (fFoundAlerts) {\n ALERTS[alert_key] = alert_translation;\n }\n // Skip all entries until we find the ALERTS flag\n if (alert_key === 'ALERTS') fFoundAlerts = true;\n }\n}\nfunction parseUserAgentLang(strUA, arrLangsWithSubset) {\n if (arrLangsWithSubset.some((strLang) => strUA.includes(strLang))) {\n // Split the lang in to 'primary' and 'subset', only use the primary lang\n return strUA.substring(0, 2);\n }\n // Otherwise, just use the full language spec\n return strUA;\n}\n\n// When adding a lang remember to add it to the object translatableLanguages as well as here.\nexport const arrActiveLangs = [\n { code: 'en', emoji: '🇬🇧' },\n { code: 'fr', emoji: '🇫🇷' },\n { code: 'de', emoji: '🇩🇪' },\n { code: 'pt-pt', emoji: '🇵🇹' },\n { code: 'pt-br', emoji: '🇧🇷' },\n { code: 'ph', emoji: '🇵🇭' },\n { code: 'uwu', emoji: '🐈' },\n];\n\nexport async function start() {\n // We use this function to parse the UA lang in a safer way: for example, there's multiple `en` definitions\n // ... but we shouldn't duplicate the language files, we can instead cut the affix (US, GB) and simply use 'en'.\n // ... This logic may apply to other languages with such subsets as well, so take care of them here!\n const arrLangsWithSubset = ['en', 'fr', 'de'];\n\n const localeLang =\n window?.navigator?.userLanguage || window?.navigator?.language;\n const strLang = localeLang\n ? parseUserAgentLang(localeLang.toLowerCase(), arrLangsWithSubset)\n : undefined;\n\n // When removing you do not have to remove from translatableLanguages\n const database = await Database.getInstance();\n const { translation: localTranslation } = await database.getSettings();\n\n // Check if set in local storage\n if (localTranslation !== '') {\n setTranslation(localTranslation);\n } else {\n // Check if we support the user's browser locale\n if (arrActiveLangs.find((lang) => lang.code === strLang)) {\n setTranslation(strLang);\n } else {\n // Default to EN if the locale isn't supported yet\n console.log(\n 'i18n: Your language (' +\n strLang +\n \") is not supported yet, if you'd like to contribute translations (for rewards!) contact us on GitHub or Discord!\"\n );\n setTranslation('en');\n }\n }\n translateStaticHTML(translation);\n}\n","import { EventEmitter } from 'events';\n\nconst eventEmitter = new EventEmitter();\n\n/**\n * Get the application wide event emitter.\n * @returns {EventEmitter}\n */\nexport function getEventEmitter() {\n return eventEmitter;\n}\n","import { getNetwork } from './network.js';\nimport { getBalance, isMasternodeUTXO, getStakingBalance } from './global.js';\nimport { sleep } from './misc.js';\nimport { debug } from './settings.js';\nimport { getEventEmitter } from './event_bus.js';\n\n/**\n * @typedef {Object} cIn - An input of a Tx\n * @property {string} txid - The transaction ID\n * @property {number} vout - The output index\n */\n\n/** An Unspent Transaction Output, used as Inputs of future transactions */\nexport class UTXO {\n /**\n * @param {Object} UTXO\n * @param {String} UTXO.id - Transaction ID\n * @param {String} UTXO.path - If applicable, the HD Path of the owning address\n * @param {Number} UTXO.sats - Satoshi value in this UTXO\n * @param {String} UTXO.script - HEX encoded spending script\n * @param {Array?} UTXO.vin - The inputs of the transaction, if any\n * @param {Number} UTXO.vout - Output position of this transaction\n * @param {Number} UTXO.height - Block height of the UTXO\n * @param {Number} UTXO.status - UTXO status enum state\n * @param {boolean} UTXO.isDelegate - Whether the UTXO is a cold stake delegation\n * @param {boolean} UTXO.isReward - Whether the UTXO is a reward\n */\n constructor({\n id,\n path,\n sats,\n script,\n vin = [],\n vout,\n height,\n status,\n isDelegate = false,\n isReward = false,\n } = {}) {\n /** Transaction ID\n * @type {String} */\n this.id = id;\n\n /** HD Path of the owning address\n * @type {String} */\n this.path = path;\n\n /** Satoshi value in this UTXO\n * @type {Number} */\n this.sats = sats;\n\n /** HEX encoded spending script\n * @type {String} */\n this.script = script;\n\n /** The inputs of the transaction, if any\n * @type {Array} */\n this.vin = vin;\n\n /** Output position of this transaction\n * @type {Number} */\n this.vout = vout;\n\n /** Block height of the UTXO\n * @type {Number} */\n this.height = height;\n\n /** UTXO status enum state\n * @type {Number} */\n this.status = status;\n\n /** Whether it's a delegation UTXO\n * @type {boolean} */\n this.isDelegate = isDelegate;\n\n /** Whether it's a reward UTXO\n * @type {boolean} */\n this.isReward = isReward;\n }\n\n /**\n * Check for equality between this UTXO and another UTXO\n * @param {UTXO} cUTXO - UTXO to compare against\n * @returns {Boolean} `true` if equal, `false` if unequal\n */\n equalsUTXO(cUTXO) {\n return (\n this.id === cUTXO.id &&\n this.vout === cUTXO.vout &&\n this.status === cUTXO.status\n );\n }\n}\n\n/** A Mempool instance, stores and handles UTXO data for the wallet */\nexport class Mempool {\n constructor() {\n /**\n * An array of all known UTXOs\n * @type {Array}\n */\n this.UTXOs = [];\n this.subscribeToNetwork();\n }\n\n /** The CONFIRMED state (UTXO is spendable) */\n static CONFIRMED = 0;\n\n /** The REMOVED state (UTXO was spent and will be removed soon) */\n static REMOVED = 1;\n\n /** The PENDING state (standard UTXO is in mempool, pending confirmation) */\n static PENDING = 2;\n\n /**\n * Fetch a UTXO by ID and Index\n * @param {string} id - Transaction ID of the UTXO\n * @param {number} out - Output position of the UTXO\n */\n getUTXO(id, out) {\n return this.UTXOs.find(\n (cUTXO) => cUTXO.id === id && cUTXO.vout === out\n );\n }\n\n /**\n * Remove a UTXO after a set amount of time\n * @param {Number} nBlocks - Estimated blocks to wait\n * @param {UTXO} cUTXO - UTXO to remove\n */\n async removeWithDelay(nBlocks, cUTXO) {\n await sleep(nBlocks * 60 * 1000);\n this.removeUTXO(cUTXO);\n }\n\n /**\n * Check if an exact UTXO match can be found in our wallet\n * @param {Object} UTXO\n * @param {String} UTXO.id - Transaction ID\n * @param {Number} UTXO.vout - Output position of this transaction\n * @param {Number} [UTXO.status] - UTXO status enum state. If it's undefined, it will ignore it.\n * @returns {Boolean} `true` or `false`\n */\n isAlreadyStored({ id, vout, status }) {\n return this.UTXOs.some(\n (cUTXO) =>\n cUTXO.id === id &&\n cUTXO.vout === vout &&\n (!status || cUTXO.status === status)\n );\n }\n\n /**\n * Fetches an array of UTXOs filtered by their state\n * @param {Number} nState - Specific UTXO state\n * @returns {Array} `array` - An array of UTXOs\n */\n getUTXOsByState(nState) {\n return this.UTXOs.filter((cUTXO) => cUTXO.status === nState);\n }\n\n /**\n * Removes a UTXO from a specific state\n * @param {UTXO} cNewUTXO - Pending UTXO to remove\n * @param {Number} nState - Specific state of this UTXO to search for\n */\n removeFromState(cNewUTXO, nState) {\n const arrPendingUTXOs = this.getUTXOsByState(nState);\n // Loop each pending UTXO\n for (const cUTXO of arrPendingUTXOs) {\n // Search for matching ID + output number\n if (cUTXO.id === cNewUTXO.id && cUTXO.vout === cNewUTXO.vout) {\n // Nuke it from orbit\n this.removeUTXO(cUTXO);\n break;\n }\n }\n }\n\n /**\n * Add a new UTXO to the wallet\n * @param {UTXO} UTXO\n */\n addUTXO({\n id,\n path,\n sats,\n script,\n vin,\n vout,\n height,\n status,\n isDelegate,\n isReward,\n }) {\n const newUTXO = new UTXO({\n id,\n path,\n sats,\n script,\n vin,\n vout,\n height,\n status,\n isDelegate,\n isReward,\n });\n\n if (this.isAlreadyStored({ id, vout })) {\n this.updateUTXO({ id, vout });\n } else {\n // If this new UTXO is a reward with one vin (i.e: a Stake), we'll backtrace the input\n if (isReward && vin?.length === 1) {\n const cStakeInput = this.getUTXO(vin[0].txid, vin[0].vout);\n\n // And if the input is in our wallet, remove it\n if (cStakeInput) {\n this.removeUTXO(cStakeInput);\n }\n }\n this.UTXOs.push(newUTXO);\n }\n\n // Re-render the Balance UIs\n getBalance(true);\n getStakingBalance(true);\n }\n\n /**\n * Update an existing UTXO, by confirming its pending status\n * The UTXO must be in\n * @param {Object} UTXO - Object to be deconstructed\n * @param {String} UTXO.id - Transaction id\n * @param {Number} UTXO.vout - vout\n */\n updateUTXO({ id, vout }) {\n if (debug) {\n console.assert(\n this.isAlreadyStored({ id, vout }),\n 'Debug Mode: updateUTXO must be called with an existing UTXO'\n );\n }\n const cUTXO = this.UTXOs.find(\n (utxo) => utxo.id === id && utxo.vout == vout\n );\n switch (cUTXO.status) {\n case Mempool.PENDING:\n cUTXO.status = Mempool.CONFIRMED;\n break;\n }\n getBalance(true);\n getStakingBalance(true);\n }\n\n /**\n * Remove a UTXO completely from our wallet\n * @param {UTXO} cUTXO - UTXO to remove\n */\n removeUTXO(cUTXO) {\n this.UTXOs = this.UTXOs.filter((utxo) => !utxo.equalsUTXO(cUTXO));\n }\n\n /**\n * Remove a UTXO completely from our wallet, with a 12 minute delay given his id, path and vout\n * @param {Object} UTXO\n * @param {String} UTXO.id - Transaction ID\n * @param {Number} UTXO.vout - Output position of this transaction\n */\n autoRemoveUTXO({ id, vout }) {\n for (const cUTXO of this.UTXOs) {\n // Loop given + internal UTXOs to find a match, then start the delayed removal\n if (cUTXO.id === id && cUTXO.vout === vout) {\n cUTXO.status = Mempool.REMOVED;\n this.removeWithDelay(12, cUTXO);\n return;\n }\n }\n console.error(\n 'Mempool: Failed to find UTXO ' +\n id +\n ' (' +\n vout +\n ') for auto-removal!'\n );\n }\n\n /**\n * Remove many UTXOs completely from our wallet, with a 12 minute delay\n * @param {Array} arrUTXOs - UTXOs to remove\n */\n autoRemoveUTXOs(arrUTXOs) {\n for (const cNewUTXO of arrUTXOs) {\n for (const cUTXO of this.UTXOs) {\n // Loop given + internal UTXOs to find a match, then start the delayed removal\n if (cUTXO.equalsUTXO(cNewUTXO)) {\n cUTXO.status = Mempool.REMOVED;\n this.removeWithDelay(12, cUTXO);\n break;\n }\n }\n }\n }\n\n /**\n * Fetches an array of confirmed UTXOs, an easier alias to {@link getUTXOsByState}\n * @returns {Array} `array` - An array of UTXOs\n */\n getConfirmed() {\n return this.getUTXOsByState(Mempool.CONFIRMED);\n }\n\n /**\n * Get standard, non delegated, UTXOs\n * @returns {Array} Non delegated utxos\n */\n getStandardUTXOs() {\n return this.UTXOs.filter(\n (cUTXO) => cUTXO.status !== Mempool.REMOVED && !cUTXO.isDelegate\n );\n }\n\n /**\n * Get delegated UTXOs\n * @returns {Array} Delegated UTXOs\n */\n getDelegatedUTXOs() {\n return this.UTXOs.filter(\n (cUTXO) => cUTXO.status !== Mempool.REMOVED && cUTXO.isDelegate\n );\n }\n\n /**\n * Returns the real-time balance of the wallet (all addresses)\n * @returns {Number} Balance in satoshis\n */\n getBalance() {\n // Fetch 'standard' balances: the sum of all Confirmed or Unconfirmed transactions (excluding Masternode collaterals)\n return this.getStandardUTXOs()\n .filter((cUTXO) => !isMasternodeUTXO(cUTXO)) // TODO: add masternode\n .reduce((a, b) => a + b.sats, 0);\n }\n\n /**\n * Returns if a UTXO is valid\n * @param {UTXO} cUTXO - UTXO\n * @returns {Boolean} `true` if the reward UTXO is spendable, `false` if not\n */\n static isValidUTXO(cUTXO) {\n if (cUTXO.isReward) {\n return getNetwork().cachedBlockCount - cUTXO.height > 100;\n } else {\n return true;\n }\n }\n\n /**\n * Returns the real-time delegated balance of the wallet (all addresses)\n * @returns {Number} Delegated balance in satoshis\n */\n getDelegatedBalance() {\n return this.getDelegatedUTXOs().reduce((a, b) => a + b.sats, 0);\n }\n\n /**\n * Subscribes to network events\n * @param {Network} network\n */\n subscribeToNetwork() {\n getEventEmitter().on('utxo', async (utxos) => {\n for (const utxo of utxos) {\n // If we have the UTXO, we update it's confirmation status\n if (this.isAlreadyStored({ id: utxo.txid, vout: utxo.vout })) {\n this.updateUTXO({ id: utxo.txid, vout: utxo.vout });\n continue;\n }\n // If the UTXO is new, we'll process it and add it internally\n this.addUTXO(await getNetwork().getUTXOFullInfo(utxo));\n }\n });\n }\n}\n","import { Mempool } from './mempool.js';\nimport Masternode from './masternode.js';\nimport { ALERTS, tr, start as i18nStart, translation } from './i18n.js';\nimport * as jdenticon from 'jdenticon';\nimport {\n masterKey,\n hasEncryptedWallet,\n importWallet,\n encryptWallet,\n decryptWallet,\n getNewAddress,\n getDerivationPath,\n LegacyMasterKey,\n} from './wallet.js';\nimport { getNetwork, HistoricalTxType } from './network.js';\nimport {\n start as settingsStart,\n cExplorer,\n debug,\n cMarket,\n strCurrency,\n setColdStakingAddress,\n strColdStakingAddress,\n nDisplayDecimals,\n fAdvancedMode,\n} from './settings.js';\nimport { createAndSendTransaction, signTransaction } from './transactions.js';\nimport {\n createAlert,\n confirmPopup,\n sanitizeHTML,\n MAP_B58,\n parseBIP21Request,\n isValidBech32,\n isBase64,\n sleep,\n beautifyNumber,\n isStandardAddress,\n} from './misc.js';\nimport { cChainParams, COIN, MIN_PASS_LENGTH } from './chain_params.js';\nimport { decrypt } from './aes-gcm.js';\n\nimport { registerWorker } from './native.js';\nimport { refreshPriceDisplay } from './prices.js';\nimport { Address6 } from 'ip-address';\nimport { getEventEmitter } from './event_bus.js';\nimport { scanQRCode } from './scanner.js';\nimport { Database } from './database.js';\nimport bitjs from './bitTrx.js';\nimport { checkForUpgrades } from './changelog.js';\nimport { FlipDown } from './flipdown.js';\nimport {\n cReceiveType,\n getNameOrAddress,\n guiAddContactPrompt,\n guiCheckRecipientInput,\n guiToggleReceiveType,\n} from './contacts-book.js';\nimport { Buffer } from 'buffer';\nimport { Account } from './accounts.js';\n\n/** A flag showing if base MPW is fully loaded or not */\nexport let fIsLoaded = false;\n\n/** A getter for the flag showing if base MPW is fully loaded or not */\nexport function isLoaded() {\n return fIsLoaded;\n}\n\nexport let doms = {};\n\nexport async function start() {\n doms = {\n domNavbarToggler: document.getElementById('navbarToggler'),\n domDashboard: document.getElementById('dashboard'),\n domGuiStaking: document.getElementById('guiStaking'),\n domGuiWallet: document.getElementById('guiWallet'),\n domGettingStartedBtn: document.getElementById('gettingStartedBtn'),\n domGuiBalance: document.getElementById('guiBalance'),\n domGuiBalanceTicker: document.getElementById('guiBalanceTicker'),\n domGuiBalanceValue: document.getElementById('guiBalanceValue'),\n domGuiBalanceValueCurrency: document.getElementById(\n 'guiBalanceValueCurrency'\n ),\n domGuiStakingValue: document.getElementById('guiStakingValue'),\n domGuiStakingValueCurrency: document.getElementById(\n 'guiStakingValueCurrency'\n ),\n domGuiBalanceBox: document.getElementById('guiBalanceBox'),\n domBalanceReload: document.getElementById('balanceReload'),\n domBalanceReloadStaking: document.getElementById(\n 'balanceReloadStaking'\n ),\n domGuiBalanceStaking: document.getElementById('guiBalanceStaking'),\n domGuiBalanceStakingTicker: document.getElementById(\n 'guiBalanceStakingTicker'\n ),\n domGuiStakingLoadMore: document.getElementById('stakingLoadMore'),\n domGuiStakingLoadMoreIcon: document.getElementById(\n 'stakingLoadMoreIcon'\n ),\n domGuiBalanceBoxStaking: document.getElementById(\n 'guiBalanceBoxStaking'\n ),\n domStakeAmount: document.getElementById('delegateAmount'),\n domUnstakeAmount: document.getElementById('undelegateAmount'),\n domStakeTab: document.getElementById('stakeTab'),\n domAddress1s: document.getElementById('address1s'),\n domSendAmountCoins: document.getElementById('sendAmountCoins'),\n domSendAmountCoinsTicker: document.getElementById(\n 'sendAmountCoinsTicker'\n ),\n domSendAmountValue: document.getElementById('sendAmountValue'),\n domSendAmountValueCurrency: document.getElementById(\n 'sendAmountValueCurrency'\n ),\n domStakeAmountCoinsTicker: document.getElementById(\n 'stakeAmountCoinsTicker'\n ),\n domStakeAmountValueCurrency: document.getElementById(\n 'stakeAmountValueCurrency'\n ),\n domStakeAmountValue: document.getElementById('stakeAmountValue'),\n domUnstakeAmountCoinsTicker: document.getElementById(\n 'unstakeAmountCoinsTicker'\n ),\n domUnstakeAmountValueCurrency: document.getElementById(\n 'unstakeAmountValueCurrency'\n ),\n\n domUnstakeAmountValue: document.getElementById('unstakeAmountValue'),\n domGuiViewKey: document.getElementById('guiViewKey'),\n domModalQR: document.getElementById('ModalQR'),\n domModalQrLabel: document.getElementById('ModalQRLabel'),\n domModalQrReceiveTypeBtn: document.getElementById(\n 'ModalQRReceiveTypeBtn'\n ),\n domModalQRReader: document.getElementById('qrReaderModal'),\n domQrReaderStream: document.getElementById('qrReaderStream'),\n domCloseQrReaderBtn: document.getElementById('closeQrReader'),\n domModalWalletBreakdown: document.getElementById(\n 'walletBreakdownModal'\n ),\n domWalletBreakdownCanvas: document.getElementById(\n 'walletBreakdownCanvas'\n ),\n domPrefix: document.getElementById('prefix'),\n domPrefixNetwork: document.getElementById('prefixNetwork'),\n domWalletToggle: document.getElementById('wToggle'),\n domGenerateWallet: document.getElementById('generateWallet'),\n domGenVanityWallet: document.getElementById('generateVanityWallet'),\n domGenHardwareWallet: document.getElementById('generateHardwareWallet'),\n //GOVERNANCE ELEMENTS\n domGovTab: document.getElementById('governanceTab'),\n domGovProposalsTable: document.getElementById('proposalsTable'),\n domGovProposalsTableBody: document.getElementById('proposalsTableBody'),\n domTotalGovernanceBudget: document.getElementById(\n 'totalGovernanceBudget'\n ),\n domTotalGovernanceBudgetValue: document.getElementById(\n 'totalGovernanceBudgetValue'\n ),\n domAllocatedGovernanceBudget: document.getElementById(\n 'allocatedGovernanceBudget'\n ),\n domAllocatedGovernanceBudgetValue: document.getElementById(\n 'allocatedGovernanceBudgetValue'\n ),\n domAllocatedGovernanceBudget2: document.getElementById(\n 'allocatedGovernanceBudget2'\n ),\n domAllocatedGovernanceBudgetValue2: document.getElementById(\n 'allocatedGovernanceBudgetValue2'\n ),\n domGovProposalsContestedTable: document.getElementById(\n 'proposalsContestedTable'\n ),\n domGovProposalsContestedTableBody: document.getElementById(\n 'proposalsContestedTableBody'\n ),\n //MASTERNODE ELEMENTS\n domCreateMasternode: document.getElementById('createMasternode'),\n domControlMasternode: document.getElementById('controlMasternode'),\n domAccessMasternode: document.getElementById('accessMasternode'),\n domMnAccessMasternodeText: document.getElementById(\n 'accessMasternodeText'\n ),\n domMnCreateType: document.getElementById('mnCreateType'),\n domMnTextErrors: document.getElementById('mnTextErrors'),\n domMnIP: document.getElementById('mnIP'),\n domMnTxId: document.getElementById('mnTxId'),\n domMnPrivateKey: document.getElementById('mnPrivateKey'),\n domMnDashboard: document.getElementById('mnDashboard'),\n domMnProtocol: document.getElementById('mnProtocol'),\n domMnStatus: document.getElementById('mnStatus'),\n domMnNetType: document.getElementById('mnNetType'),\n domMnNetIP: document.getElementById('mnNetIP'),\n domMnLastSeen: document.getElementById('mnLastSeen'),\n\n domAccessWallet: document.getElementById('accessWallet'),\n domImportWallet: document.getElementById('importWallet'),\n domImportWalletText: document.getElementById('importWalletText'),\n domAccessWalletBtn: document.getElementById('accessWalletBtn'),\n domVanityUiButtonTxt: document.getElementById('vanButtonText'),\n domGenKeyWarning: document.getElementById('genKeyWarning'),\n domEncryptWalletLabel: document.getElementById('encryptWalletLabel'),\n domEncryptPasswordCurrent: document.getElementById(\n 'changePassword-current'\n ),\n domEncryptPasswordBox: document.getElementById('encryptPassword'),\n domEncryptPasswordFirst: document.getElementById('newPassword'),\n domEncryptPasswordSecond: document.getElementById('newPasswordRetype'),\n domGuiAddress: document.getElementById('guiAddress'),\n domGenIt: document.getElementById('genIt'),\n domReqDesc: document.getElementById('reqDesc'),\n domReqDisplay: document.getElementById('reqDescDisplay'),\n domIdenticon: document.getElementById('identicon'),\n domPrivKey: document.getElementById('privateKey'),\n domPrivKeyPassword: document.getElementById('privateKeyPassword'),\n domAvailToDelegate: document.getElementById('availToDelegate'),\n domAvailToUndelegate: document.getElementById('availToUndelegate'),\n domAnalyticsDescriptor: document.getElementById('analyticsDescriptor'),\n domStakingRewardsList: document.getElementById(\n 'staking-rewards-content'\n ),\n domStakingRewardsTitle: document.getElementById(\n 'staking-rewards-title'\n ),\n domMnemonicModalContent: document.getElementById(\n 'ModalMnemonicContent'\n ),\n domMnemonicModalButton: document.getElementById(\n 'modalMnemonicConfirmButton'\n ),\n domMnemonicModalPassphrase: document.getElementById(\n 'ModalMnemonicPassphrase'\n ),\n domExportPrivateKey: document.getElementById('exportPrivateKeyText'),\n domExportWallet: document.getElementById('guiExportWalletItem'),\n domWipeWallet: document.getElementById('guiWipeWallet'),\n domRestoreWallet: document.getElementById('guiRestoreWallet'),\n domNewAddress: document.getElementById('guiNewAddress'),\n domRedeemTitle: document.getElementById('redeemCodeModalTitle'),\n domRedeemCodeUse: document.getElementById('redeemCodeUse'),\n domRedeemCodeCreate: document.getElementById('redeemCodeCreate'),\n domRedeemCodeGiftIconBox: document.getElementById(\n 'redeemCodeGiftIconBox'\n ),\n domRedeemCodeGiftIcon: document.getElementById('redeemCodeGiftIcon'),\n domRedeemCodeETA: document.getElementById('redeemCodeETA'),\n domRedeemCodeProgress: document.getElementById('redeemCodeProgress'),\n domRedeemCodeInputBox: document.getElementById('redeemCodeInputBox'),\n domRedeemCodeInput: document.getElementById('redeemCodeInput'),\n domRedeemCodeConfirmBtn: document.getElementById(\n 'redeemCodeModalConfirmButton'\n ),\n domRedeemCodeModeRedeemBtn: document.getElementById(\n 'redeemCodeModeRedeem'\n ),\n domRedeemCodeModeCreateBtn: document.getElementById(\n 'redeemCodeModeCreate'\n ),\n domRedeemCodeCreateInput: document.getElementById(\n 'redeemCodeCreateInput'\n ),\n domRedeemCodeCreateAmountInput: document.getElementById(\n 'redeemCodeCreateAmountInput'\n ),\n domRedeemCodeCreatePendingList: document.getElementById(\n 'redeemCodeCreatePendingList'\n ),\n domPromoTable: document.getElementById('promo-table'),\n domContactsTable: document.getElementById('contactsList'),\n domActivityList: document.getElementById('activity-list-content'),\n domActivityLoadMore: document.getElementById('activityLoadMore'),\n domActivityLoadMoreIcon: document.getElementById(\n 'activityLoadMoreIcon'\n ),\n domConfirmModalDialog: document.getElementById('confirmModalDialog'),\n domConfirmModalMain: document.getElementById('confirmModalMain'),\n domConfirmModalHeader: document.getElementById('confirmModalHeader'),\n domConfirmModalTitle: document.getElementById('confirmModalTitle'),\n domConfirmModalContent: document.getElementById('confirmModalContent'),\n domConfirmModalButtons: document.getElementById('confirmModalButtons'),\n domConfirmModalConfirmButton: document.getElementById(\n 'confirmModalConfirmButton'\n ),\n domConfirmModalCancelButton: document.getElementById(\n 'confirmModalCancelButton'\n ),\n\n masternodeLegacyAccessText:\n 'Access the masternode linked to this address
Note: the masternode MUST have been already created (however it can be online or offline)
If you want to create a new masternode access with a HD wallet',\n masternodeHDAccessText:\n \"Access your masternodes if you have any! If you don't you can create one\",\n // Aggregate menu screens and links for faster switching\n arrDomScreens: document.getElementsByClassName('tabcontent'),\n arrDomScreenLinks: document.getElementsByClassName('tablinks'),\n // Alert DOM element\n domAlertPos: document.getElementsByClassName('alertPositioning')[0],\n domNetwork: document.getElementById('Network'),\n domChangePasswordContainer: document.getElementById(\n 'changePassword-container'\n ),\n domDebug: document.getElementById('Debug'),\n domTestnet: document.getElementById('Testnet'),\n domCurrencySelect: document.getElementById('currency'),\n domExplorerSelect: document.getElementById('explorer'),\n domNodeSelect: document.getElementById('node'),\n domAutoSwitchToggle: document.getElementById('autoSwitchToggler'),\n domTranslationSelect: document.getElementById('translation'),\n domDisplayDecimalsSlider: document.getElementById('displayDecimals'),\n domDisplayDecimalsSliderDisplay:\n document.getElementById('sliderDisplay'),\n domBlackBack: document.getElementById('blackBack'),\n domWalletSettings: document.getElementById('settingsWallet'),\n domDisplaySettings: document.getElementById('settingsDisplay'),\n domWalletSettingsBtn: document.getElementById('settingsWalletBtn'),\n domDisplaySettingsBtn: document.getElementById('settingsDisplayBtn'),\n domVersion: document.getElementById('version'),\n domFlipdown: document.getElementById('flipdown'),\n domTestnetToggler: document.getElementById('testnetToggler'),\n domAdvancedModeToggler: document.getElementById('advancedModeToggler'),\n };\n await i18nStart();\n await loadImages();\n\n // Enable all Bootstrap Tooltips\n $(function () {\n $('#displayDecimals').tooltip({\n template:\n '
',\n });\n $('[data-toggle=\"tooltip\"]').tooltip();\n });\n\n // Set decimal slider event\n const sliderElement = document.getElementById('displayDecimals');\n function handleDecimalSlider() {\n setTimeout(() => {\n try {\n if (window.innerWidth > 991) {\n const sliderHalf = Math.round(\n document\n .getElementById('displayDecimals')\n .getBoundingClientRect().width / 2\n );\n const sliderBegin = -sliderHalf + 28;\n const stepVal = (sliderHalf * 2) / 8 - 6.45;\n const sliderValue = parseInt(sliderElement.value) + 1;\n\n document.querySelector('.sliderStyle').style.left = `${\n sliderBegin - stepVal + stepVal * sliderValue\n }px`;\n document.querySelector('.tooltip-inner').innerHTML =\n sliderValue - 1;\n }\n } catch (e) {}\n }, 10);\n }\n sliderElement.addEventListener('input', handleDecimalSlider);\n sliderElement.addEventListener('mouseover', handleDecimalSlider);\n\n // Register Input Pair events\n doms.domSendAmountCoins.oninput = () => {\n updateAmountInputPair(\n doms.domSendAmountCoins,\n doms.domSendAmountValue,\n true\n );\n };\n doms.domSendAmountValue.oninput = () => {\n updateAmountInputPair(\n doms.domSendAmountCoins,\n doms.domSendAmountValue,\n false\n );\n };\n\n /** Staking (Stake) */\n doms.domStakeAmount.oninput = () => {\n updateAmountInputPair(\n doms.domStakeAmount,\n doms.domStakeAmountValue,\n true\n );\n };\n doms.domStakeAmountValue.oninput = () => {\n updateAmountInputPair(\n doms.domStakeAmount,\n doms.domStakeAmountValue,\n false\n );\n };\n\n /** Staking (Unstake) */\n doms.domUnstakeAmount.oninput = () => {\n updateAmountInputPair(\n doms.domUnstakeAmount,\n doms.domUnstakeAmountValue,\n true\n );\n };\n doms.domUnstakeAmountValue.oninput = () => {\n updateAmountInputPair(\n doms.domUnstakeAmount,\n doms.domUnstakeAmountValue,\n false\n );\n };\n\n // Register native app service\n registerWorker();\n\n // Configure Identicon\n jdenticon.configure();\n\n // URL-Query request processing\n const urlParams = new URLSearchParams(window.location.search);\n\n // Check for a payment request address\n const reqTo = urlParams.has('pay') ? urlParams.get('pay') : '';\n\n // Check for a payment request amount\n const reqAmount = urlParams.has('amount')\n ? parseFloat(urlParams.get('amount'))\n : 0;\n await settingsStart();\n\n // Customise the UI if a saved wallet exists\n if (await hasEncryptedWallet()) {\n // Hide the 'Generate wallet' buttons\n doms.domGenerateWallet.style.display = 'none';\n doms.domGenVanityWallet.style.display = 'none';\n const database = await Database.getInstance();\n const { publicKey } = await database.getAccount();\n\n // Import the wallet, and toggle the startup flag, which delegates the chain data refresh to settingsStart();\n if (publicKey) {\n await importWallet({ newWif: publicKey, fStartup: true });\n\n // Update the \"Receive\" UI to apply Translation and Contacts updates\n await guiToggleReceiveType(cReceiveType);\n\n // Check for Add Contact calls\n if (urlParams.has('addcontact')) {\n // Quick sanity check\n const strURI = urlParams.get('addcontact');\n if (strURI.includes(':')) {\n // Split to 'name' and 'pubkey'\n const arrParts = strURI.split(':');\n\n // Convert Name from HEX to UTF-8\n const strName = Buffer.from(arrParts[0], 'hex').toString(\n 'utf8'\n );\n const strPubkey = arrParts[1];\n\n // Prompt the user to add the Contact\n guiAddContactPrompt(sanitizeHTML(strName), strPubkey);\n }\n } else if (reqTo.length || reqAmount > 0) {\n // Payment processor popup\n guiPreparePayment(\n reqTo,\n reqAmount,\n urlParams.has('desc') ? urlParams.get('desc') : ''\n );\n }\n } else {\n // Display the password unlock upfront\n await accessOrImportWallet();\n }\n } else {\n // Just load the block count, for use in non-wallet areas\n getNetwork().getBlockCount();\n }\n\n subscribeToNetworkEvents();\n\n doms.domPrefix.value = '';\n doms.domPrefixNetwork.innerText =\n cChainParams.current.PUBKEY_PREFIX.join(' or ');\n // If allowed by settings: submit a simple 'hit' (app load) to Labs Analytics\n getNetwork().submitAnalytics('hit');\n setInterval(() => {\n // Refresh blockchain data\n refreshChainData();\n\n // Fetch the PIVX prices\n refreshPriceDisplay();\n }, 15000);\n\n // After reaching here; we know MPW's base is fully loaded!\n fIsLoaded = true;\n\n // Check for recent upgrades, display the changelog\n checkForUpgrades();\n\n // If we haven't already (due to having no wallet, etc), display the Dashboard\n doms.domDashboard.click();\n\n // Update the Encryption UI (If the user has a wallet, then it changes to \"Change Password\" rather than \"Encrypt Wallet\")\n await updateEncryptionGUI();\n}\n\nfunction subscribeToNetworkEvents() {\n getEventEmitter().on('network-toggle', (value) => {\n doms.domNetwork.innerHTML =\n '';\n });\n\n getEventEmitter().on('sync-status', (value) => {\n switch (value) {\n case 'start':\n // Play reload anim\n doms.domBalanceReload.classList.add('playAnim');\n doms.domBalanceReloadStaking.classList.add('playAnim');\n break;\n case 'stop':\n doms.domBalanceReload.classList.remove('playAnim');\n doms.domBalanceReloadStaking.classList.remove('playAnim');\n break;\n }\n });\n\n getEventEmitter().on('transaction-sent', (success, result) => {\n if (success) {\n doms.domAddress1s.value = '';\n doms.domSendAmountCoins.innerHTML = '';\n createAlert(\n 'success',\n `${ALERTS.TX_SENT}
${sanitizeHTML(result)}`,\n result ? 1250 + result.length * 50 : 3000\n );\n // If allowed by settings: submit a simple 'tx' ping to Labs Analytics\n getNetwork().submitAnalytics('transaction');\n } else {\n console.error('Error sending transaction:');\n console.error(result);\n createAlert('warning', ALERTS.TX_FAILED, 2500);\n }\n });\n}\n\n// WALLET STATE DATA\nexport const mempool = new Mempool();\nlet exportHidden = false;\nlet isTestnetLastState = cChainParams.current.isTestnet;\n\n/**\n * @type {FlipDown | null}\n */\nlet governanceFlipdown = null;\n\n/**\n * Open a UI 'tab' menu, and close all other tabs, intended for frontend use\n * @param {Event} evt - The click event target\n * @param {string} tabName - The name of the tab to load\n */\nexport function openTab(evt, tabName) {\n // Only allow switching tabs if MPw is loaded\n if (!isLoaded()) return;\n\n // Hide all screens and deactivate link highlights\n for (const domScreen of doms.arrDomScreens)\n domScreen.style.display = 'none';\n for (const domLink of doms.arrDomScreenLinks)\n domLink.classList.remove('active');\n\n // Show and activate the given screen\n document.getElementById(tabName).style.display = 'block';\n evt.currentTarget.classList.add('active');\n\n // Close the navbar if it's not already closed\n if (!doms.domNavbarToggler.className.includes('collapsed'))\n doms.domNavbarToggler.click();\n\n if (tabName === 'Governance') {\n updateGovernanceTab();\n } else if (tabName === 'Masternode') {\n updateMasternodeTab();\n } else if (\n tabName === 'StakingTab' &&\n getNetwork().arrTxHistory.length === 0\n ) {\n // Refresh the TX list\n updateActivityGUI(true, false);\n } else if (\n tabName === 'keypair' &&\n getNetwork().arrTxHistory.length === 0\n ) {\n // Refresh the TX list\n updateActivityGUI(false, false);\n }\n}\n\n/**\n * Updates the GUI ticker among all elements; useful for Network Switching\n */\nexport function updateTicker() {\n // Update the Dashboard currency\n doms.domGuiBalanceValueCurrency.innerText = strCurrency.toUpperCase();\n\n // Update the Stake Dashboard currency\n doms.domGuiStakingValueCurrency.innerText = strCurrency.toUpperCase();\n\n // Update the Send menu ticker and currency\n doms.domSendAmountValueCurrency.innerText = strCurrency.toUpperCase();\n doms.domSendAmountCoinsTicker.innerText = cChainParams.current.TICKER;\n\n // Update the Stake/Unstake menu ticker and currency\n // Stake\n doms.domStakeAmountValueCurrency.innerText = strCurrency.toUpperCase();\n doms.domStakeAmountCoinsTicker.innerText = cChainParams.current.TICKER;\n\n // Unstake\n doms.domUnstakeAmountValueCurrency.innerText = strCurrency.toUpperCase();\n doms.domUnstakeAmountCoinsTicker.innerText = cChainParams.current.TICKER;\n}\n\n/**\n * Return locale settings best for displaying the user-selected currency\n * @param {Number} nAmount - The amount in Currency\n */\nexport function optimiseCurrencyLocale(nAmount) {\n // Allow manipulating the value, if necessary\n let nValue = nAmount;\n\n // Find the best fitting native-locale\n const cLocale = Intl.supportedValuesOf('currency').includes(\n strCurrency.toUpperCase()\n )\n ? {\n style: 'currency',\n currency: strCurrency,\n currencyDisplay: 'narrowSymbol',\n }\n : { maximumFractionDigits: 8, minimumFractionDigits: 8 };\n\n // Catch display edge-cases; like Satoshis having decimals.\n switch (strCurrency) {\n case 'sats':\n nValue = Math.round(nValue);\n cLocale.maximumFractionDigits = 0;\n cLocale.minimumFractionDigits = 0;\n }\n\n // Return display-optimised Value and Locale pair.\n return { nValue, cLocale };\n}\n\n/**\n * Update a 'price value' DOM display for the given balance type\n * @param {HTMLElement} domValue\n * @param {boolean} fCold\n */\nexport async function updatePriceDisplay(domValue, fCold = false) {\n // Update currency values\n const nPrice = await cMarket.getPrice(strCurrency);\n\n if (nPrice) {\n // Calculate the value\n const nCurrencyValue =\n ((fCold ? getStakingBalance() : getBalance()) / COIN) * nPrice;\n\n const { nValue, cLocale } = optimiseCurrencyLocale(nCurrencyValue);\n\n // Update the DOM\n domValue.innerText = nValue.toLocaleString('en-gb', cLocale);\n }\n}\n\nexport function getBalance(updateGUI = false) {\n const nBalance = mempool.getBalance();\n const nCoins = nBalance / COIN;\n\n // Update the GUI too, if chosen\n if (updateGUI) {\n // Set the balance, and adjust font-size for large balance strings\n const strBal = nCoins.toFixed(nDisplayDecimals);\n const nLen = strBal.length;\n doms.domGuiBalance.innerHTML = beautifyNumber(\n strBal,\n nLen >= 10 ? '17px' : '25px'\n );\n doms.domAvailToDelegate.innerHTML =\n beautifyNumber(strBal) + ' ' + cChainParams.current.TICKER;\n\n // Update tickers\n updateTicker();\n\n // Update price displays\n updatePriceDisplay(doms.domGuiBalanceValue);\n }\n\n return nBalance;\n}\n\nexport function getStakingBalance(updateGUI = false) {\n const nBalance = mempool.getDelegatedBalance();\n const nCoins = nBalance / COIN;\n\n if (updateGUI) {\n // Set the balance, and adjust font-size for large balance strings\n const strBal = nCoins.toFixed(nDisplayDecimals);\n const nLen = strBal.length;\n doms.domGuiBalanceStaking.innerHTML = beautifyNumber(\n strBal,\n nLen >= 10 ? '17px' : '25px'\n );\n doms.domAvailToUndelegate.innerHTML =\n beautifyNumber(strBal) + ' ' + cChainParams.current.TICKER;\n\n // Update tickers\n updateTicker();\n\n // Update price displays\n updatePriceDisplay(doms.domGuiStakingValue, true);\n }\n\n return nBalance;\n}\n\n/**\n * Fill a 'Coin Amount' with all of a balance type, and update the 'Coin Value'\n * @param {HTMLInputElement} domCoin - The 'Coin Amount' input element\n * @param {HTMLInputElement} domValue - Th 'Coin Value' input element\n * @param {boolean} fCold - Use the Cold Staking balance, or Available balance\n */\nexport function selectMaxBalance(domCoin, domValue, fCold = false) {\n domCoin.value = (fCold ? getStakingBalance() : getBalance()) / COIN;\n // Update the Send menu's value (assumption: if it's not a Cold balance, it's probably for Sending!)\n updateAmountInputPair(domCoin, domValue, true);\n}\n\n/**\n * Prompt a QR scan for a Payment (Address or BIP21)\n */\nexport async function openSendQRScanner() {\n const cScan = await scanQRCode();\n\n if (!cScan || !cScan.data) return;\n\n /* Check what data the scan contains - for the various QR request types */\n\n // Plain address (Length and prefix matches)\n if (isStandardAddress(cScan.data)) {\n return guiPreparePayment(cScan.data);\n }\n\n // Shield address (Valid bech32 string)\n if (isValidBech32(cScan.data).valid) {\n return guiPreparePayment(cScan.data);\n }\n\n // BIP21 Payment Request (Optional 'amount' and 'label')\n const cBIP21Req = parseBIP21Request(cScan.data);\n if (cBIP21Req) {\n return guiPreparePayment(\n cBIP21Req.address,\n cBIP21Req.options.amount || 0,\n cBIP21Req.options.label || ''\n );\n }\n\n // MPW Contact Request URI\n if (cScan.data.includes('addcontact=')) {\n // Parse as URL Params\n const cURL = new URL(cScan.data);\n const urlParams = new URLSearchParams(cURL.search);\n const strURI = urlParams.get('addcontact');\n\n // Sanity check the URI\n if (strURI?.includes(':')) {\n // Split to 'name' and 'pubkey'\n const arrParts = strURI.split(':');\n\n // If the wallet is encrypted, prompt the user to (optionally) add the Contact, before the Tx\n const fUseName = (await hasEncryptedWallet())\n ? await guiAddContactPrompt(\n sanitizeHTML(arrParts[0]),\n arrParts[1],\n false\n )\n : false;\n\n // Prompt for payment\n return guiPreparePayment(fUseName ? arrParts[0] : arrParts[1]);\n }\n }\n\n // No idea what this is...\n createAlert(\n 'warning',\n `\"${sanitizeHTML(\n cScan.data.substring(0, Math.min(cScan.data.length, 6))\n )}…\" ${ALERTS.QR_SCANNER_BAD_RECEIVER}`,\n 7500\n );\n}\n\n/**\n * Generate a DOM-optimised activity list\n * @param {Array} arrTXs - The TX array to compute the list from\n * @param {boolean} fRewards - If this list is for Reward transactions\n * @returns {Promise} HTML - The Activity List in HTML string form\n */\nexport async function createActivityListHTML(arrTXs, fRewards = false) {\n const cNet = getNetwork();\n const cDB = await Database.getInstance();\n const cAccount = await cDB.getAccount();\n\n // Prepare the table HTML\n let strList = `\n \n \n \n \n \n \n \n \n \n `;\n\n // Prepare time formatting\n const dateOptions = {\n year: '2-digit',\n month: '2-digit',\n day: '2-digit',\n };\n const timeOptions = {\n hour: '2-digit',\n minute: '2-digit',\n hour12: true,\n };\n\n // And also keep track of our last Tx's timestamp, to re-use a cache, which is much faster than the slow `.toLocaleDateString`\n let prevDateString = '';\n let prevTimestamp = 0;\n\n // Generate the TX list\n for (const cTx of arrTXs) {\n // If no account is loaded, we render nothing!\n if (!masterKey) break;\n\n const dateTime = new Date(cTx.time * 1000);\n\n // If this Tx is older than 24h, then hit the `Date` cache logic, otherwise, use a `Time` and skip it\n let strDate =\n Date.now() / 1000 - cTx.time > 86400\n ? ''\n : dateTime.toLocaleTimeString(undefined, timeOptions);\n if (!strDate) {\n if (\n prevDateString &&\n prevTimestamp - cTx.time * 1000 < 12 * 60 * 60 * 1000\n ) {\n // Use our date cache\n strDate = prevDateString;\n } else {\n // Create a new date, this Tx is too old to use the cache\n prevDateString = dateTime.toLocaleDateString(\n undefined,\n dateOptions\n );\n strDate = prevDateString;\n }\n }\n\n // Update the time cache\n prevTimestamp = cTx.time * 1000;\n\n // Coinbase Transactions (rewards) require 100 confs\n const fConfirmed =\n cNet.cachedBlockCount - cTx.blockHeight >= fRewards ? 100 : 6;\n\n // Choose the correct icon and colour for the Tx type, or a question mark if the type is unknown\n // Defaults: Reward Activity\n let icon = 'fa-gift';\n let colour = 'white';\n\n // Choose the content type, for the Dashboard; use a generative description, otherwise, a TX-ID\n let txContent = fRewards ? cTx.id : translation.activityBlockReward;\n\n // Format the amount to reduce text size\n let formattedAmt = '';\n if (cTx.amount < 0.01) {\n formattedAmt = '<0.01';\n } else if (cTx.amount >= 100) {\n formattedAmt = Math.round(cTx.amount).toString();\n } else {\n formattedAmt = cTx.amount.toFixed(2);\n }\n\n // For 'Send' or 'Receive' TXs: Check if this is a send-to-self transaction\n let fSendToSelf = true;\n if (\n cTx.type === HistoricalTxType.SENT ||\n cTx.type === HistoricalTxType.RECEIVED\n ) {\n // Check all addresses to find our own, caching them for performance\n for (const strAddr of cTx.receivers.concat(cTx.senders)) {\n // If a previous Tx checked this address, skip it, otherwise, check it against our own address(es)\n if (!(await masterKey.isOwnAddress(strAddr))) {\n // External address, this is not a self-only Tx\n fSendToSelf = false;\n }\n }\n }\n\n // Generate an icon, colour and description for the Tx\n if (!fRewards) {\n switch (cTx.type) {\n case HistoricalTxType.STAKE:\n icon = 'fa-gift';\n break;\n case HistoricalTxType.SENT:\n icon = 'fa-minus';\n colour = '#f93c3c';\n // Figure out WHO this was sent to, and focus on them contextually\n if (fSendToSelf) {\n txContent = translation.activitySentToSelf;\n } else {\n // Otherwise, anything to us is likely change, so filter it away\n const arrExternalAddresses = (\n await Promise.all(\n cTx.receivers.map(async (addr) => [\n await masterKey.isOwnAddress(addr),\n addr,\n ])\n )\n )\n .filter(([isOwnAddress, _]) => {\n return !isOwnAddress;\n })\n .map(([_, addr]) =>\n getNameOrAddress(cAccount, addr)\n );\n txContent =\n translation.activitySentTo +\n ' ' +\n (cTx.shieldedOutputs\n ? translation.activityShieldedAddress\n : [\n ...new Set(\n arrExternalAddresses.map((addr) =>\n addr.length >= 32\n ? addr.substring(0, 6)\n : addr\n )\n ),\n ].join(', ') + '...');\n }\n break;\n case HistoricalTxType.RECEIVED: {\n icon = 'fa-plus';\n colour = '#5cff5c';\n // Figure out WHO this was sent from, and focus on them contextually\n // Filter away any of our own addresses\n const arrExternalAddresses = (\n await Promise.all(\n cTx.senders.map(async (addr) => [\n await masterKey.isOwnAddress(addr),\n addr,\n ])\n )\n )\n .filter(([isOwnAddress, _]) => {\n return !isOwnAddress;\n })\n .map(([_, addr]) => getNameOrAddress(cAccount, addr));\n\n if (cTx.shieldedOutputs) {\n txContent = translation.activityReceivedShield;\n } else {\n txContent =\n translation.activityReceivedFrom +\n ' ' +\n [\n ...new Set(\n arrExternalAddresses.map((addr) =>\n addr?.length >= 32\n ? addr.substring(0, 6)\n : addr\n )\n ),\n ].join(', ') +\n '...';\n }\n break;\n }\n case HistoricalTxType.DELEGATION:\n icon = 'fa-snowflake';\n txContent =\n translation.activityDelegatedTo +\n ' ' +\n cTx.receivers[0].substring(0, 6) +\n '...';\n break;\n case HistoricalTxType.UNDELEGATION:\n icon = 'fa-fire';\n txContent = translation.activityUndelegated;\n break;\n default:\n icon = 'fa-question';\n txContent = translation.activityUnknown;\n }\n }\n\n // Render the list element from Tx data\n strList += `\n \n \n \n \n \n `;\n }\n\n // End the table\n strList += `
${translation.time}${\n fRewards ? translation.ID : translation.description\n }${translation.amount}
\n ${strDate}\n \n \n ${sanitizeHTML(\n txContent\n )}\n \n \n ${formattedAmt} ${\n cChainParams.current.TICKER\n }\n \n ${\n fConfirmed\n ? ''\n : ``\n }\n
`;\n\n // Return the HTML string\n return strList;\n}\n\n/**\n * Refreshes the specified activity table, charts and related information\n */\nexport async function updateActivityGUI(fStaking = false, fNewOnly = false) {\n const cNet = getNetwork();\n\n // Prevent the user from spamming refreshes\n if (cNet.historySyncing) return;\n\n // Remember how much history we had previously\n const nPrevHistory = cNet.arrTxHistory.length;\n\n // Choose the Dashboard or Staking UI accordingly\n let domLoadMore = doms.domActivityLoadMore;\n let domLoadMoreIcon = doms.domActivityLoadMoreIcon;\n if (fStaking) {\n domLoadMore = doms.domGuiStakingLoadMore;\n domLoadMoreIcon = doms.domGuiStakingLoadMoreIcon;\n }\n\n // Load rewards from the network, displaying the sync spin icon until finished\n domLoadMoreIcon.classList.add('fa-spin');\n const arrTXs = await cNet.syncTxHistoryChunk(fNewOnly);\n domLoadMoreIcon.classList.remove('fa-spin');\n\n // If there's no change in history size post-sync, then we can cancel here, there's nothing new to render\n if (nPrevHistory === cNet.arrTxHistory.length) return;\n\n // Check if all transactions are loaded\n if (cNet.isHistorySynced) {\n // Hide the load more button\n domLoadMore.style.display = 'none';\n }\n\n // Render the new Activity lists\n renderActivityGUI(arrTXs);\n}\n\n/**\n * Renders the Activity GUIs (without syncing or refreshing)\n * @param {Array} arrTXs\n */\nexport async function renderActivityGUI(arrTXs) {\n // For Staking: Filter the list for only Stakes, display total rewards from known history\n const cNet = getNetwork();\n const arrStakes = arrTXs.filter((a) => a.type === HistoricalTxType.STAKE);\n const nRewards = arrStakes.reduce((a, b) => a + b.amount, 0);\n doms.domStakingRewardsTitle.innerHTML = `${\n cNet.isHistorySynced ? '' : '≥'\n }${sanitizeHTML(nRewards)} ${cChainParams.current.TICKER}`;\n\n // Create and render the Dashboard Activity\n doms.domActivityList.innerHTML = await createActivityListHTML(\n arrTXs,\n false\n );\n // Create and render the Staking History\n doms.domStakingRewardsList.innerHTML = await createActivityListHTML(\n arrStakes,\n true\n );\n}\n\n/**\n * Open the Explorer in a new tab for the current wallet, or a specific address\n * @param {string?} strAddress - Optional address to open, if void, the master key is used\n */\nexport async function openExplorer(strAddress = '') {\n if (masterKey?.isHD && !strAddress) {\n const derivationPath = getDerivationPath(masterKey.isHardwareWallet)\n .split('/')\n .slice(0, 4)\n .join('/');\n const xpub = await masterKey.getxpub(derivationPath);\n window.open(cExplorer.url + '/xpub/' + xpub, '_blank');\n } else {\n const address = strAddress || (await masterKey.getAddress());\n window.open(cExplorer.url + '/address/' + address, '_blank');\n }\n}\n\nasync function loadImages() {\n const images = [\n ['mpw-main-logo', import('../assets/logo.png')],\n ['privateKeyImage', import('../assets/key.png')],\n ];\n\n const promises = images.map(([id, path]) =>\n (async () => {\n document.getElementById(id).src = (await path).default;\n })()\n );\n await Promise.all(promises);\n}\n\nlet audio = null;\nexport async function playMusic() {\n // On first play: load the audio into memory from the host\n if (audio === null) {\n // Dynamically load the file\n audio = new Audio((await import('../assets/music.mp3')).default);\n }\n\n // Play or Pause\n if (audio.paused || audio.ended) {\n audio.play();\n for (const domImg of document.getElementsByTagName('img'))\n domImg.classList.add('discoFilter');\n } else {\n audio.pause();\n for (const domImg of document.getElementsByTagName('img'))\n domImg.classList.remove('discoFilter');\n }\n}\n\nexport function unblurPrivKey() {\n if (\n document\n .getElementById('exportPrivateKeyText')\n .classList.contains('blurred')\n ) {\n document\n .getElementById('exportPrivateKeyText')\n .classList.remove('blurred');\n } else {\n document\n .getElementById('exportPrivateKeyText')\n .classList.add('blurred');\n }\n}\n\nexport function toggleBottomMenu(dom, ani) {\n let element = document.getElementById(dom);\n if (element.classList.contains(ani)) {\n element.classList.remove(ani);\n doms.domBlackBack.classList.remove('d-none');\n setTimeout(() => {\n doms.domBlackBack.classList.remove('blackBackHide');\n }, 10);\n } else {\n element.classList.add(ani);\n doms.domBlackBack.classList.add('blackBackHide');\n setTimeout(() => {\n doms.domBlackBack.classList.add('d-none');\n }, 150);\n }\n}\n\n/**\n * Updates an Amount Input UI pair ('Coin' and 'Value' input boxes) in relation to the input box used\n * @param {HTMLInputElement} domCoin - The DOM input for the Coin amount\n * @param {HTMLInputElement} domValue - The DOM input for the Value amount\n * @param {boolean} fCoinEdited - `true` if Coin, `false` if Value\n */\nexport async function updateAmountInputPair(domCoin, domValue, fCoinEdited) {\n // Fetch the price in the user's preferred currency\n const nPrice = await cMarket.getPrice(strCurrency);\n\n // If there is no price loaded, then we just won't do anything\n if (!nPrice) return;\n\n if (fCoinEdited) {\n // If the 'Coin' input is edited, then update the 'Value' input with it's converted currency\n const nValue = Number(domCoin.value) * nPrice;\n domValue.value = nValue <= 0 ? '' : nValue;\n } else {\n // If the 'Value' input is edited, then update the 'Coin' input with the reversed conversion rate\n const nValue = Number(domValue.value) / nPrice;\n domCoin.value = nValue <= 0 ? '' : nValue;\n }\n}\n\nexport function toClipboard(source, caller) {\n // Fetch the text/value source\n const domCopy = document.getElementById(source) || source;\n\n // Use an invisible textbox as the clipboard source\n const domClipboard = document.getElementById('clipboard');\n domClipboard.value = domCopy.value || domCopy.innerHTML || domCopy;\n domClipboard.select();\n domClipboard.setSelectionRange(0, 99999);\n\n // Browser-dependent clipboard execution\n if (!navigator.clipboard) {\n document.execCommand('copy');\n } else {\n navigator.clipboard.writeText(domCopy.innerHTML || domCopy);\n }\n\n // Display a temporary checkmark response\n caller.classList.add('fa-check');\n caller.classList.remove('fa-clipboard');\n caller.style.cursor = 'default';\n setTimeout(() => {\n caller.classList.add('fa-clipboard');\n caller.classList.remove('fa-check');\n caller.style.cursor = 'pointer';\n }, 1000);\n}\n\n/**\n * Prompt for a payment in the GUI with pre-filled inputs\n * @param {string} strTo - The address receiving the payment\n * @param {number} nAmount - The payment amount in full coins\n * @param {string} strDesc - The payment message or description\n */\nexport function guiPreparePayment(strTo = '', nAmount = 0, strDesc = '') {\n // Apply values\n doms.domAddress1s.value = strTo;\n doms.domSendAmountCoins.value = nAmount;\n doms.domReqDesc.value = strDesc;\n doms.domReqDisplay.style.display = strDesc ? 'block' : 'none';\n\n // Switch to the Dashboard\n doms.domDashboard.click();\n\n // Open the Send menu, if not already open (with a small timeout post-load to allow for CSS loading)\n if (\n document\n .getElementById('transferMenu')\n .classList.contains('transferAnimation')\n ) {\n setTimeout(() => {\n toggleBottomMenu('transferMenu', 'transferAnimation');\n }, 300);\n }\n\n // Update the conversion value\n updateAmountInputPair(\n doms.domSendAmountCoins,\n doms.domSendAmountValue,\n true\n );\n\n // Run the Input Validity checker\n guiCheckRecipientInput({ target: doms.domAddress1s });\n\n // Focus on the coin input box (if no pre-fill was specified)\n if (nAmount <= 0) {\n doms.domSendAmountCoins.focus();\n }\n}\n\n/**\n * Set the \"Wallet Options\" menu visibility\n * @param {String} strDisplayCSS - The `display` CSS option to set the Wallet Options to\n */\nexport function setDisplayForAllWalletOptions(strDisplayCSS) {\n // Set the display and Reset the Vanity address input\n doms.domPrefix.value = '';\n doms.domPrefix.style.display = strDisplayCSS;\n\n // Set all \"*Wallet\" buttons\n doms.domGenerateWallet.style.display = strDisplayCSS;\n doms.domImportWallet.style.display = strDisplayCSS;\n doms.domGenVanityWallet.style.display = strDisplayCSS;\n doms.domAccessWallet.style.display = strDisplayCSS;\n doms.domGenHardwareWallet.style.display = strDisplayCSS;\n}\n\nexport async function govVote(hash, voteCode) {\n if (\n (await confirmPopup({\n title: ALERTS.CONFIRM_POPUP_VOTE,\n html: ALERTS.CONFIRM_POPUP_VOTE_HTML,\n })) == true\n ) {\n const database = await Database.getInstance();\n const cMasternode = await database.getMasternode();\n if (cMasternode) {\n if ((await cMasternode.getStatus()) !== 'ENABLED') {\n createAlert('warning', ALERTS.MN_NOT_ENABLED, 6000);\n return;\n }\n const result = await cMasternode.vote(hash.toString(), voteCode); //1 yes 2 no\n if (result.includes('Voted successfully')) {\n //good vote\n cMasternode.storeVote(hash.toString(), voteCode);\n await updateGovernanceTab();\n createAlert('success', ALERTS.VOTE_SUBMITTED, 6000);\n } else if (result.includes('Error voting :')) {\n //If you already voted return an alert\n createAlert('warning', ALERTS.VOTED_ALREADY, 6000);\n } else if (result.includes('Failure to verify signature.')) {\n //wrong masternode private key\n createAlert('warning', ALERTS.VOTE_SIG_BAD, 6000);\n } else {\n //this could be everything\n console.error(result);\n createAlert('warning', ALERTS.INTERNAL_ERROR, 6000);\n }\n } else {\n createAlert('warning', ALERTS.MN_ACCESS_BEFORE_VOTE, 6000);\n }\n }\n}\n\n/**\n * Start a Masternode via a signed network broadcast\n * @param {boolean} fRestart - Whether this is a Restart or a first Start\n */\nexport async function startMasternode(fRestart = false) {\n const database = await Database.getInstance();\n const cMasternode = await database.getMasternode(masterKey);\n if (cMasternode) {\n if (\n masterKey.isViewOnly &&\n !(await restoreWallet(translation.walletUnlockMNStart))\n )\n return;\n if (await cMasternode.start()) {\n const strMsg = fRestart ? ALERTS.MN_RESTARTED : ALERTS.MN_STARTED;\n createAlert('success', strMsg, 4000);\n } else {\n const strMsg = fRestart\n ? ALERTS.MN_RESTART_FAILED\n : ALERTS.MN_START_FAILED;\n createAlert('warning', strMsg, 4000);\n }\n }\n}\n\nexport async function destroyMasternode() {\n const database = await Database.getInstance();\n\n if (await database.getMasternode(masterKey)) {\n database.removeMasternode(masterKey);\n createAlert('success', ALERTS.MN_DESTROYED, 5000);\n updateMasternodeTab();\n }\n}\n\n/**\n * Takes an ip address and adds the port.\n * If it's a tor address, ip.onion:port will be used (e.g. expyuzz4wqqyqhjn.onion:12345)\n * If it's an IPv4 address, ip:port will be used, (e.g. 127.0.0.1:12345)\n * If it's an IPv6 address, [ip]:port will be used, (e.g. [::1]:12345)\n * @param {String} ip - Ip address with or without port\n * @returns {String}\n */\nfunction parseIpAddress(ip) {\n // IPv4 or tor without port\n if (ip.match(/\\d+\\.\\d+\\.\\d+\\.\\d+/) || ip.match(/\\w+\\.onion/)) {\n return `${ip}:${cChainParams.current.MASTERNODE_PORT}`;\n }\n\n // IPv4 or tor with port\n if (ip.match(/\\d+\\.\\d+\\.\\d+\\.\\d+:\\d+/) || ip.match(/\\w+\\.onion:\\d+/)) {\n return ip;\n }\n\n // IPv6 without port\n if (Address6.isValid(ip)) {\n return `[${ip}]:${cChainParams.current.MASTERNODE_PORT}`;\n }\n\n const groups = /\\[(.*)\\]:\\d+/.exec(ip);\n if (groups !== null && groups.length > 1) {\n // IPv6 with port\n if (Address6.isValid(groups[1])) {\n return ip;\n }\n }\n\n // If we haven't returned yet, the address was invalid.\n return null;\n}\n\nexport async function importMasternode() {\n const mnPrivKey = doms.domMnPrivateKey.value;\n const address = parseIpAddress(doms.domMnIP.value);\n if (!address) {\n createAlert('warning', ALERTS.MN_BAD_IP, 5000);\n return;\n }\n\n let collateralTxId;\n let outidx;\n let collateralPrivKeyPath;\n doms.domMnIP.value = '';\n doms.domMnPrivateKey.value = '';\n\n if (!masterKey.isHD) {\n // Find the first UTXO matching the expected collateral size\n const cCollaUTXO = mempool\n .getConfirmed()\n .find(\n (cUTXO) => cUTXO.sats === cChainParams.current.collateralInSats\n );\n\n // If there's no valid UTXO, exit with a contextual message\n if (!cCollaUTXO) {\n if (getBalance(false) < cChainParams.current.collateralInSats) {\n // Not enough balance to create an MN UTXO\n const amount =\n (cChainParams.current.collateralInSats -\n getBalance(false)) /\n COIN;\n const ticker = cChainParams.current.TICKER;\n createAlert(\n 'warning',\n tr(ALERTS.MN_NOT_ENOUGH_COLLAT, [\n { amount: amount },\n { ticker: ticker },\n ]),\n 10000\n );\n } else {\n // Balance is capable of a masternode, just needs to be created\n // TODO: this UX flow is weird, is it even possible? perhaps we can re-design this entire function accordingly\n const amount = cChainParams.current.collateralInSats / COIN;\n const ticker = cChainParams.current.TICKER;\n createAlert(\n 'warning',\n tr(ALERTS.MN_ENOUGH_BUT_NO_COLLAT, [\n { amount },\n { ticker },\n ]),\n 10000\n );\n }\n return;\n }\n\n collateralTxId = cCollaUTXO.id;\n outidx = cCollaUTXO.vout;\n collateralPrivKeyPath = 'legacy';\n } else {\n const path = doms.domMnTxId.value;\n const masterUtxo = mempool\n .getConfirmed()\n .findLast((u) => u.path === path); // first UTXO for each address in HD\n // sanity check:\n if (masterUtxo.sats !== cChainParams.current.collateralInSats) {\n return createAlert('warning', ALERTS.MN_COLLAT_NOT_SUITABLE, 10000);\n }\n collateralTxId = masterUtxo.id;\n outidx = masterUtxo.vout;\n collateralPrivKeyPath = path;\n }\n doms.domMnTxId.value = '';\n\n const cMasternode = new Masternode({\n walletPrivateKeyPath: collateralPrivKeyPath,\n mnPrivateKey: mnPrivKey,\n collateralTxId: collateralTxId,\n outidx: outidx,\n addr: address,\n });\n await refreshMasternodeData(cMasternode, true);\n await updateMasternodeTab();\n}\n\nexport async function accessOrImportWallet() {\n // Hide and Reset the Vanity address input\n doms.domPrefix.value = '';\n doms.domPrefix.style.display = 'none';\n\n // Show Import button, hide access button\n doms.domImportWallet.style.display = 'block';\n setTimeout(() => {\n doms.domPrivKey.style.opacity = '1';\n }, 100);\n doms.domAccessWalletBtn.style.display = 'none';\n\n // If we have a local wallet, display the decryption prompt\n // This is no longer being used, as the user will be put in view-only\n // mode when logging in, however if the user locked the wallet before\n // #52 there would be no way to recover the public key without getting\n // The password from the user\n if (await hasEncryptedWallet()) {\n doms.domPrivKey.placeholder = translation.encryptPasswordFirst;\n doms.domImportWalletText.innerText = translation.unlockWallet;\n doms.domPrivKey.focus();\n }\n}\n/**\n * An event function triggered apon private key UI input changes\n *\n * Useful for adjusting the input types or displaying password prompts depending on the import scheme\n */\nexport async function guiUpdateImportInput() {\n if (await hasEncryptedWallet()) return;\n // Check whether the string is Base64 (would likely be an MPW-encrypted import)\n // and it doesn't have any spaces (would be a mnemonic seed)\n const fContainsSpaces = doms.domPrivKey.value.trim().includes(' ');\n\n // If this could require a Seed Passphrase (BIP39 Passphrase) and Advanced Mode is enabled\n // ...or if this is an Encrypted Import (Encrypted Base64 MPW key)\n const fBIP39Passphrase = fContainsSpaces && fAdvancedMode;\n doms.domPrivKeyPassword.hidden =\n (doms.domPrivKey.value.length < 128 ||\n !isBase64(doms.domPrivKey.value)) &&\n !fBIP39Passphrase;\n\n doms.domPrivKeyPassword.placeholder = fContainsSpaces\n ? translation.optionalPassphrase\n : translation.password;\n\n // If the \"Import Password/Passphrase\" is hidden, we'll also wipe it's input, in the\n // ... edge-case that a passphrase was entered, then the import key had changed.\n if (doms.domPrivKeyPassword.hidden) doms.domPrivKeyPassword.value = '';\n\n // Uncloak the private input IF spaces are detected, to make Seed Phrases easier to input and verify\n doms.domPrivKey.setAttribute('type', fContainsSpaces ? 'text' : 'password');\n}\n\n/**\n * Imports a wallet using the GUI input, handling decryption via UI\n */\nexport async function guiImportWallet() {\n // Important: These fields will be wiped by importWallet();\n const strPrivKey = doms.domPrivKey.value;\n const strPassword = doms.domPrivKeyPassword.value;\n const fEncrypted = strPrivKey.length >= 128 && isBase64(strPrivKey);\n\n // If we are in testnet: prompt an import\n if (cChainParams.current.isTestnet) return importWallet();\n\n // If we don't have a DB wallet and the input is plain: prompt an import\n if (!(await hasEncryptedWallet()) && !fEncrypted) return importWallet();\n\n // If we don't have a DB wallet and the input is ciphered:\n if (!(await hasEncryptedWallet()) && fEncrypted) {\n const strDecWIF = await decrypt(strPrivKey, strPassword);\n if (!strDecWIF || strDecWIF === 'decryption failed!') {\n return createAlert('warning', ALERTS.FAILED_TO_IMPORT, 6000);\n } else {\n await importWallet({\n newWif: strDecWIF,\n // Save the public key to disk for future View Only mode post-decryption\n fSavePublicKey: true,\n });\n\n if (masterKey) {\n // Prepare a new Account to add\n const cAccount = new Account({\n publicKey: await masterKey.keyToExport,\n encWif: strPrivKey,\n });\n\n // Add the new Account to the DB\n const database = await Database.getInstance();\n database.addAccount(cAccount);\n }\n\n // Destroy residue import data\n doms.domPrivKey.value = '';\n doms.domPrivKeyPassword.value = '';\n return;\n }\n }\n // Prompt for decryption of the existing wallet\n const fHasWallet = await decryptWallet(doms.domPrivKey.value);\n\n // If the wallet was successfully loaded, hide all options and load the dash!\n if (fHasWallet) setDisplayForAllWalletOptions('none');\n}\n\nexport async function guiEncryptWallet() {\n // Fetch our inputs, ensure they're of decent entropy + match eachother\n const strPass = doms.domEncryptPasswordFirst.value,\n strPassRetype = doms.domEncryptPasswordSecond.value;\n if (strPass.length < MIN_PASS_LENGTH)\n return createAlert(\n 'warning',\n tr(ALERTS.PASSWORD_TOO_SMALL, [\n { MIN_PASS_LENGTH: MIN_PASS_LENGTH },\n ]),\n 4000\n );\n if (strPass !== strPassRetype)\n return createAlert('warning', ALERTS.PASSWORD_DOESNT_MATCH, 2250);\n\n // If this wallet is already encrypted, then we'll check for the current password and ensure it decrypts properly too\n if (await hasEncryptedWallet()) {\n // Grab the pass, and wipe the dialog immediately\n const strCurrentPass = doms.domEncryptPasswordCurrent.value;\n doms.domEncryptPasswordCurrent.value = '';\n\n // If the decryption fails: we don't allow changing the password\n if (!(await decryptWallet(strCurrentPass))) return;\n }\n\n // Encrypt the wallet using the new password\n await encryptWallet(strPass);\n createAlert('success', ALERTS.NEW_PASSWORD_SUCCESS, 5500);\n\n // Hide and reset the encryption modal\n $('#encryptWalletModal').modal('hide');\n doms.domEncryptPasswordFirst.value = '';\n doms.domEncryptPasswordSecond.value = '';\n\n // Display the 'Unlock/Lock Wallet' buttons accordingly based on state\n doms.domWipeWallet.hidden = masterKey.isViewOnly;\n doms.domRestoreWallet.hidden = !masterKey.isViewOnly;\n\n // Update the encryption UI (changes to \"Change Password\" now)\n await updateEncryptionGUI(true);\n}\n\n/** Update the \"Encrypt Wallet\" / \"Change Password\" dialog to match the current wallet state */\nexport async function updateEncryptionGUI(fEncrypted = null) {\n // If no param is provided, check if a wallet exists in the database\n if (fEncrypted === null) {\n fEncrypted = await hasEncryptedWallet();\n }\n // If the wallet is encrypted, we display a \"Current Password\" input in the Encryption dialog, otherwise, only accept New Passwords\n doms.domEncryptPasswordCurrent.style.display = fEncrypted ? '' : 'none';\n // And we adjust the displays to accomodate the mode as well\n doms.domEncryptWalletLabel.innerText = fEncrypted\n ? translation.changePassword\n : translation.encryptWallet;\n doms.domChangePasswordContainer.style.display = fEncrypted ? '' : 'none';\n}\n\nexport async function toggleExportUI() {\n if (!exportHidden) {\n if (await hasEncryptedWallet()) {\n const { encWif } = await (\n await Database.getInstance()\n ).getAccount();\n doms.domExportPrivateKey.innerHTML = encWif;\n exportHidden = true;\n } else {\n if (masterKey.isViewOnly) {\n exportHidden = false;\n } else {\n doms.domExportPrivateKey.innerHTML = masterKey.keyToBackup;\n exportHidden = true;\n }\n }\n } else {\n doms.domExportPrivateKey.innerHTML = '';\n exportHidden = false;\n }\n}\n\nexport function checkVanity() {\n var e = event || window.event; // get event object\n var key = e.keyCode || e.which; // get key cross-browser\n var char = String.fromCharCode(key).trim(); // convert key to char\n if (char.length == 0) return;\n\n // Ensure the input is base58 compatible\n if (!MAP_B58.toLowerCase().includes(char.toLowerCase())) {\n if (e.preventDefault) e.preventDefault();\n e.returnValue = false;\n return createAlert(\n 'warning',\n tr(ALERTS.UNSUPPORTED_CHARACTER, [{ char: char }]),\n 3500\n );\n }\n}\n\nlet isVanityGenerating = false;\nconst arrWorkers = [];\nlet vanUiUpdater;\n\nfunction stopSearch() {\n isVanityGenerating = false;\n for (let thread of arrWorkers) {\n thread.terminate();\n }\n while (arrWorkers.length) arrWorkers.pop();\n doms.domPrefix.disabled = false;\n doms.domVanityUiButtonTxt.innerText = translation.dCardTwoButton;\n clearInterval(vanUiUpdater);\n}\n\nexport async function generateVanityWallet() {\n if (isVanityGenerating) return stopSearch();\n if (typeof Worker === 'undefined')\n return createAlert('error', ALERTS.UNSUPPORTED_WEBWORKERS, 7500);\n // Generate a vanity address with the given prefix\n if (\n doms.domPrefix.value.length === 0 ||\n doms.domPrefix.style.display === 'none'\n ) {\n // No prefix, display the intro!\n doms.domPrefix.style.display = 'block';\n setTimeout(() => {\n doms.domPrefix.style.opacity = '1';\n }, 100);\n doms.domPrefix.focus();\n } else {\n // Remove spaces from prefix\n doms.domPrefix.value = doms.domPrefix.value.replace(/ /g, '');\n\n // Cache a lowercase equivilent for lower-entropy comparisons (a case-insensitive search is ALOT faster!) and strip accidental spaces\n const nInsensitivePrefix = doms.domPrefix.value.toLowerCase();\n const nPrefixLen = nInsensitivePrefix.length;\n\n // Ensure the input is base58 compatible\n for (const char of doms.domPrefix.value) {\n if (!MAP_B58.toLowerCase().includes(char.toLowerCase()))\n return createAlert(\n 'warning',\n tr(ALERTS.UNSUPPORTED_CHARACTER, [{ char: char }]),\n 3500\n );\n // We also don't want users to be mining addresses for years... so cap the letters to four until the generator is more optimized\n if (doms.domPrefix.value.length > 5)\n return createAlert(\n 'warning',\n tr(ALERTS.UNSUPPORTED_CHARACTER, [{ char: char }]),\n 3500\n );\n }\n isVanityGenerating = true;\n doms.domPrefix.disabled = true;\n let attempts = 0;\n\n // Setup workers\n const nThreads = Math.max(\n Math.floor(window.navigator.hardwareConcurrency * 0.75),\n 1\n );\n console.log('Spawning ' + nThreads + ' vanity search threads!');\n while (arrWorkers.length < nThreads) {\n arrWorkers.push(\n new Worker(new URL('./vanitygen_worker.js', import.meta.url))\n );\n const checkResult = (data) => {\n attempts++;\n if (\n data.pub.substr(1, nPrefixLen).toLowerCase() ==\n nInsensitivePrefix\n ) {\n importWallet({\n newWif: data.priv,\n fRaw: true,\n });\n stopSearch();\n doms.domGuiBalance.innerHTML = '0';\n return console.log(\n 'VANITY: Found an address after ' +\n attempts +\n ' attempts!'\n );\n }\n };\n\n arrWorkers[arrWorkers.length - 1].onmessage = (event) =>\n checkResult(event.data);\n arrWorkers[arrWorkers.length - 1].postMessage(\n cChainParams.current.PUBKEY_ADDRESS\n );\n }\n\n // GUI Updater\n doms.domVanityUiButtonTxt.innerText =\n 'Stop (Searched ' + attempts.toLocaleString('en-GB') + ' keys)';\n vanUiUpdater = setInterval(() => {\n doms.domVanityUiButtonTxt.innerText =\n 'Stop (Searched ' + attempts.toLocaleString('en-GB') + ' keys)';\n }, 200);\n }\n}\n\n/**\n * Sweep an address to our own wallet, spending all it's UTXOs without change\n * @param {Array} arrUTXOs - The UTXOs belonging to the address to sweep\n * @param {LegacyMasterKey} sweepingMasterKey - The address to sweep from\n * @param {number} nFixedFee - An optional fixed satoshi fee\n * @returns {Promise} - TXID on success, false or error on failure\n */\nexport async function sweepAddress(arrUTXOs, sweepingMasterKey, nFixedFee = 0) {\n const cTx = new bitjs.transaction();\n\n // Load all UTXOs as inputs\n let nTotal = 0;\n for (const cUTXO of arrUTXOs) {\n nTotal += cUTXO.sats;\n cTx.addinput({\n txid: cUTXO.id,\n index: cUTXO.vout,\n script: cUTXO.script,\n path: cUTXO.path,\n });\n }\n\n // Use a given fixed fee, or use the network fee if unspecified\n const nFee = nFixedFee || getNetwork().getFee(cTx.serialize().length);\n\n // Use a new address from our wallet to sweep the UTXOs in to\n const strAddress = (await getNewAddress(true, false))[0];\n\n // Sweep the full funds amount, minus the fee, leaving no change from any sweeped UTXOs\n cTx.addoutput(strAddress, (nTotal - nFee) / COIN);\n\n // Sign using the given Master Key, then broadcast the sweep, returning the TXID (or a failure)\n const sign = await signTransaction(cTx, sweepingMasterKey);\n return await getNetwork().sendTransaction(sign);\n}\n\nexport function toggleDropDown(id) {\n const domID = document.getElementById(id);\n domID.style.display = domID.style.display === 'block' ? 'none' : 'block';\n}\n\nexport function isMasternodeUTXO(cUTXO, cMasternode) {\n if (cMasternode?.collateralTxId) {\n const { collateralTxId, outidx } = cMasternode;\n return collateralTxId === cUTXO.id && cUTXO.vout === outidx;\n } else {\n return false;\n }\n}\n\n/**\n * Creates a GUI popup for the user to check or customise their Cold Address\n */\nexport async function guiSetColdStakingAddress() {\n if (\n await confirmPopup({\n title: translation.popupSetColdAddr,\n html: `

${\n translation.popupCurrentAddress\n }
${strColdStakingAddress}

${\n translation.popupColdStakeNote\n }


`,\n })\n ) {\n // Fetch address from the popup input\n const strColdAddress = document.getElementById('newColdAddress').value;\n\n // If it's empty, just return false\n if (!strColdAddress) return false;\n\n // Sanity-check, and set!\n if (\n strColdAddress[0] === cChainParams.current.STAKING_PREFIX &&\n strColdAddress.length === 34\n ) {\n await setColdStakingAddress(strColdAddress);\n createAlert('info', ALERTS.STAKE_ADDR_SET, 5000);\n return true;\n } else {\n createAlert('warning', ALERTS.STAKE_ADDR_BAD, 2500);\n return false;\n }\n } else {\n return false;\n }\n}\n\nexport async function wipePrivateData() {\n const isEncrypted = await hasEncryptedWallet();\n const title = isEncrypted\n ? translation.popupWalletLock\n : translation.popupWalletWipe;\n const html = isEncrypted\n ? translation.popupWalletLockNote\n : translation.popupWalletWipeNote;\n if (\n await confirmPopup({\n title,\n html,\n })\n ) {\n masterKey.wipePrivateData();\n doms.domWipeWallet.hidden = true;\n if (isEncrypted) {\n doms.domRestoreWallet.hidden = false;\n }\n }\n}\n\n/**\n * Prompt the user in the GUI to unlock their wallet\n * @param {string} strReason - An optional reason for the unlock\n * @returns {Promise} - If the unlock was successful or rejected\n */\nexport async function restoreWallet(strReason = '') {\n // Build up the UI elements based upon conditions for the unlock prompt\n let strHTML = '';\n\n // If there's a reason given; display it as a sub-text\n strHTML += `

${strReason}

`;\n\n // Prompt the user\n if (\n await confirmPopup({\n title: translation.walletUnlock,\n html: `${strHTML}`,\n })\n ) {\n // Fetch the password from the prompt, and immediately destroy the prompt input\n const domPassword = document.getElementById('restoreWalletPassword');\n const strPassword = domPassword.value;\n domPassword.value = '';\n\n // Attempt to unlock the wallet with the provided password\n if (await decryptWallet(strPassword)) {\n doms.domRestoreWallet.hidden = true;\n doms.domWipeWallet.hidden = false;\n // Wallet is unlocked!\n return true;\n } else {\n // Password is invalid\n return false;\n }\n } else {\n // User rejected the unlock\n return false;\n }\n}\n\n/** A lock to prevent rendering the Governance Dashboard multiple times */\nlet fRenderingGovernance = false;\n\n/**\n * Fetch Governance data and re-render the Governance UI\n */\nexport async function updateGovernanceTab() {\n if (fRenderingGovernance) return;\n fRenderingGovernance = true;\n\n // Setup the Superblock countdown (if not already done), no need to block thread with await, either.\n let cNet = getNetwork();\n\n // When switching to mainnet from testnet or vise versa, you ned to use an await on getBlockCount() or cNet.cachedBlockCount returns 0\n if (!isTestnetLastState == cChainParams.current.isTestnet) {\n // Reset flipdown\n governanceFlipdown = null;\n doms.domFlipdown.innerHTML = '';\n\n // Get new network blockcount\n await getNetwork().getBlockCount();\n cNet = getNetwork();\n }\n\n // Update governance counter when testnet/mainnet has been switched\n if (!governanceFlipdown && cNet.cachedBlockCount > 0) {\n Masternode.getNextSuperblock().then((nSuperblock) => {\n // The estimated time to the superblock (using the block target and remaining blocks)\n const nTimestamp =\n Date.now() / 1000 + (nSuperblock - cNet.cachedBlockCount) * 60;\n governanceFlipdown = new FlipDown(nTimestamp).start();\n });\n isTestnetLastState = cChainParams.current.isTestnet;\n }\n\n // Fetch all proposals from the network\n const arrProposals = await Masternode.getProposals({\n fAllowFinished: false,\n });\n\n /* Sort proposals into two categories\n - Standard (Proposal is either new with <100 votes, or has a healthy vote count)\n - Contested (When a proposal may be considered spam, malicious, or simply highly contestable)\n */\n const arrStandard = arrProposals.filter(\n (a) => a.Yeas + a.Nays < 100 || a.Ratio > 0.25\n );\n const arrContested = arrProposals.filter(\n (a) => a.Yeas + a.Nays >= 100 && a.Ratio <= 0.25\n );\n\n // Render Proposals\n await Promise.all([\n renderProposals(arrStandard, false),\n renderProposals(arrContested, true),\n ]);\n\n // Remove lock\n fRenderingGovernance = false;\n}\n\n/**\n * @typedef {Object} ProposalCache\n * @property {number} nSubmissionHeight - The submission height of the proposal.\n * @property {string} txid - The transaction ID of the proposal (string).\n * @property {boolean} fFetching - Indicates whether the proposal is currently being fetched or not.\n */\n\n/**\n * An array of Proposal Finalisation caches\n * @type {Array}\n */\nconst arrProposalFinalisationCache = [];\n\n/**\n * Asynchronously wait for a Proposal Tx to confirm, then cache the height.\n *\n * Do NOT await unless you want to lock the thread for a long time.\n * @param {ProposalCache} cProposalCache - The proposal cache to wait for\n * @returns {Promise} Returns `true` once the block height is cached\n */\nasync function waitForSubmissionBlockHeight(cProposalCache) {\n let nHeight = null;\n\n // Wait in a permanent throttled loop until we successfully fetch the block\n const cNet = getNetwork();\n while (true) {\n // If a proposal is already fetching, then consequtive calls will be rejected\n cProposalCache.fFetching = true;\n\n // Attempt to fetch the submission Tx (may not exist yet!)\n let cTx = null;\n try {\n cTx = await cNet.getTxInfo(cProposalCache.txid);\n } catch (_) {}\n\n if (!cTx || !cTx.blockHeight) {\n // Didn't get the TX, throttle the thread by sleeping for a bit, then try again.\n await sleep(30000);\n } else {\n nHeight = cTx.blockHeight;\n break;\n }\n }\n\n // Update the proposal finalisation cache\n cProposalCache.nSubmissionHeight = nHeight;\n\n return true;\n}\n\n/**\n * Create a Status String for a proposal's finalisation status\n * @param {ProposalCache} cPropCache - The proposal cache to check\n * @returns {string} The string status, for display purposes\n */\nfunction getProposalFinalisationStatus(cPropCache) {\n const cNet = getNetwork();\n const nConfsLeft = cPropCache.nSubmissionHeight + 6 - cNet.cachedBlockCount;\n\n if (cPropCache.nSubmissionHeight === 0 || cNet.cachedBlockCount === 0) {\n return translation.proposalFinalisationConfirming;\n } else if (nConfsLeft > 0) {\n return (\n nConfsLeft +\n ' block' +\n (nConfsLeft === 1 ? '' : 's') +\n ' ' +\n translation.proposalFinalisationRemaining\n );\n } else if (Math.abs(nConfsLeft) >= cChainParams.current.budgetCycleBlocks) {\n return translation.proposalFinalisationExpired;\n } else {\n return translation.proposalFinalisationReady;\n }\n}\n\n/**\n *\n * @param {Object} cProposal - A local proposal to add to the cache tracker\n * @returns {ProposalCache} - The finalisation cache object pointer of the local proposal\n */\nfunction addProposalToFinalisationCache(cProposal) {\n // If it exists, return the existing cache\n /** @type ProposalCache */\n let cPropCache = arrProposalFinalisationCache.find(\n (a) => a.txid === cProposal.mpw.txid\n );\n if (cPropCache) return cPropCache;\n\n // Create a new cache\n cPropCache = {\n nSubmissionHeight: 0,\n txid: cProposal.mpw.txid,\n fFetching: false,\n };\n arrProposalFinalisationCache.push(cPropCache);\n\n // Return the object 'pointer' in the array for further updating\n return cPropCache;\n}\n\n/**\n * Render Governance proposal objects to a given Proposal category\n * @param {Array} arrProposals - The proposals to render\n * @param {boolean} fContested - The proposal category\n */\nasync function renderProposals(arrProposals, fContested) {\n // Set the total budget\n doms.domTotalGovernanceBudget.innerText = (\n cChainParams.current.maxPayment / COIN\n ).toLocaleString('en-gb');\n\n // Update total budget in user's currency\n const nPrice = await cMarket.getPrice(strCurrency);\n const nCurrencyValue = (cChainParams.current.maxPayment / COIN) * nPrice;\n const { nValue, cLocale } = optimiseCurrencyLocale(nCurrencyValue);\n doms.domTotalGovernanceBudgetValue.innerHTML =\n nValue.toLocaleString('en-gb', cLocale) +\n ' ' +\n strCurrency.toUpperCase() +\n '';\n\n // Select the table based on the proposal category\n const domTable = fContested\n ? doms.domGovProposalsContestedTableBody\n : doms.domGovProposalsTableBody;\n\n // Render the proposals in the relevent table\n const database = await Database.getInstance();\n const cMasternode = await database.getMasternode();\n\n if (!fContested) {\n const localProposals =\n (await database.getAccount())?.localProposals?.map((p) => {\n return {\n Name: p.name,\n URL: p.url,\n PaymentAddress: p.address,\n MonthlyPayment: p.monthlyPayment / COIN,\n RemainingPaymentCount: p.nPayments,\n TotalPayment: p.nPayments * (p.monthlyPayment / COIN),\n Yeas: 0,\n Nays: 0,\n local: true,\n Ratio: 0,\n mpw: p,\n };\n }) || [];\n arrProposals = localProposals.concat(arrProposals);\n }\n arrProposals = await Promise.all(\n arrProposals.map(async (p) => {\n return {\n YourVote:\n cMasternode && p.Hash\n ? await cMasternode.getVote(p.Name, p.Hash)\n : null,\n ...p,\n };\n })\n );\n\n // Fetch the Masternode count for proposal status calculations\n const cMasternodes = await Masternode.getMasternodeCount();\n\n let totalAllocatedAmount = 0;\n\n // Wipe the current table and start rendering proposals\n let i = 0;\n domTable.innerHTML = '';\n for (const cProposal of arrProposals) {\n const domRow = domTable.insertRow();\n\n const domStatus = domRow.insertCell();\n domStatus.classList.add('governStatusCol');\n if (domTable.id == 'proposalsTableBody') {\n domStatus.setAttribute(\n 'onclick',\n `if(document.getElementById('governMob${i}').classList.contains('d-none')) { document.getElementById('governMob${i}').classList.remove('d-none'); } else { document.getElementById('governMob${i}').classList.add('d-none'); }`\n );\n } else if (domTable.id == 'proposalsContestedTableBody') {\n domStatus.setAttribute(\n 'onclick',\n `if(document.getElementById('governMobCon${i}').classList.contains('d-none')) { document.getElementById('governMobCon${i}').classList.remove('d-none'); } else { document.getElementById('governMobCon${i}').classList.add('d-none'); }`\n );\n }\n\n // Add border radius to last row\n if (arrProposals.length - 1 == i) {\n domStatus.classList.add('bblr-7p');\n }\n\n // Net Yes calculation\n const { Yeas, Nays } = cProposal;\n const nNetYes = Yeas - Nays;\n const nNetYesPercent = (nNetYes / cMasternodes.enabled) * 100;\n\n // Proposal Status calculation\n const nRequiredVotes = Math.round(cMasternodes.enabled * 0.1);\n const strStatus =\n nNetYes >= nRequiredVotes\n ? translation.proposalPassing\n : translation.proposalFailing;\n let strFundingStatus = translation.proposalNotFunded;\n\n // Funding Status and allocation calculations\n if (cProposal.local) {\n // Check the finalisation cache\n const cPropCache = addProposalToFinalisationCache(cProposal);\n if (!cPropCache.fFetching) {\n waitForSubmissionBlockHeight(cPropCache).then(\n updateGovernanceTab\n );\n }\n const strStatus = getProposalFinalisationStatus(cPropCache);\n const finalizeButton = document.createElement('button');\n finalizeButton.className = 'pivx-button-small';\n finalizeButton.innerHTML = '';\n\n if (\n strStatus === translation.proposalFinalisationReady ||\n strStatus === translation.proposalFinalisationExpired\n ) {\n finalizeButton.addEventListener('click', async () => {\n const result = await Masternode.finalizeProposal(\n cProposal.mpw\n );\n\n const deleteProposal = async () => {\n // Fetch Account\n const account = await database.getAccount();\n\n // Find index of Account local proposal to remove\n const nProposalIndex = account.localProposals.findIndex(\n (p) => p.txid === cProposal.mpw.txid\n );\n\n // If found, remove the proposal and update the account with the modified localProposals array\n if (nProposalIndex > -1) {\n // Remove our proposal from it\n account.localProposals.splice(nProposalIndex, 1);\n\n // Update the DB\n await database.updateAccount(account, true);\n }\n };\n\n if (result.ok) {\n deleteProposal();\n // Create a prompt showing the finalisation success, vote hash, and further details\n confirmPopup({\n title: translation.PROPOSAL_FINALISED + ' 🚀',\n html: `

${\n translation.popupProposalFinalisedNote\n }

${\n translation.popupProposalVoteHash\n }
${sanitizeHTML(\n result.hash\n )}

${\n translation.popupProposalFinalisedSignoff\n } 👋

`,\n hideConfirm: true,\n });\n updateGovernanceTab();\n } else {\n if (result.err === 'unconfirmed') {\n createAlert(\n 'warning',\n ALERTS.PROPOSAL_UNCONFIRMED,\n 5000\n );\n } else if (result.err === 'invalid') {\n createAlert(\n 'warning',\n ALERTS.PROPOSAL_EXPIRED,\n 5000\n );\n deleteProposal();\n updateGovernanceTab();\n } else {\n createAlert(\n 'warning',\n ALERTS.PROPOSAL_FINALISE_FAIL\n );\n }\n }\n });\n } else {\n finalizeButton.style.opacity = 0.5;\n finalizeButton.style.cursor = 'default';\n }\n\n domStatus.innerHTML = `\n \n ${strStatus}
\n
\n \n \n `;\n domStatus.appendChild(finalizeButton);\n } else {\n if (domTable.id == 'proposalsTableBody') {\n if (\n nNetYes >= nRequiredVotes &&\n totalAllocatedAmount + cProposal.MonthlyPayment <=\n cChainParams.current.maxPayment / COIN\n ) {\n strFundingStatus = translation.proposalFunded;\n totalAllocatedAmount += cProposal.MonthlyPayment;\n }\n }\n\n // Figure out the colour of the Status, if any (using CSS class `votes[Yes/No]`)\n const strColourClass =\n strStatus === translation.proposalPassing ? 'Yes' : 'No';\n\n domStatus.innerHTML = `\n \n ${strStatus}
\n (${strFundingStatus})
\n
\n \n ${nNetYesPercent.toFixed(1)}%
\n ${translation.proposalNetYes}\n
\n \n \n `;\n }\n\n // Name, Payment Address and URL hyperlink\n const domNameAndURL = domRow.insertCell();\n domNameAndURL.style = 'vertical-align: middle;';\n\n // IMPORTANT: Sanitise all of our HTML or a rogue server or malicious proposal could perform a cross-site scripting attack\n domNameAndURL.innerHTML = `${sanitizeHTML(\n cProposal.Name\n )}
${sanitizeHTML(\n cProposal.PaymentAddress.slice(0, 6) + '...'\n )}`;\n\n // Convert proposal amount to user's currency\n const nProposalValue = parseInt(cProposal.MonthlyPayment) * nPrice;\n const { nValue } = optimiseCurrencyLocale(nProposalValue);\n const strProposalCurrency = nValue.toLocaleString('en-gb', cLocale);\n\n // Payment Schedule and Amounts\n const domPayments = domRow.insertCell();\n domPayments.classList.add('for-desktop');\n domPayments.style = 'vertical-align: middle;';\n domPayments.innerHTML = `${sanitizeHTML(\n parseInt(cProposal.MonthlyPayment).toLocaleString('en-gb', ',', '.')\n )} ${\n cChainParams.current.TICKER\n }
\n (${strProposalCurrency} ${strCurrency.toUpperCase()})
\n\n ${sanitizeHTML(\n cProposal['RemainingPaymentCount']\n )} ${translation.proposalPaymentsRemaining} ${sanitizeHTML(\n parseInt(cProposal.TotalPayment).toLocaleString('en-gb', ',', '.')\n )} ${cChainParams.current.TICKER} ${\n translation.proposalPaymentTotal\n }`;\n\n // Vote Counts and Consensus Percentages\n const domVoteCounters = domRow.insertCell();\n domVoteCounters.classList.add('for-desktop');\n domVoteCounters.style = 'vertical-align: middle;';\n\n const nLocalPercent = cProposal.Ratio * 100;\n domVoteCounters.innerHTML = `${parseFloat(\n nLocalPercent\n ).toLocaleString(\n 'en-gb',\n { minimumFractionDigits: 0, maximumFractionDigits: 1 },\n ',',\n '.'\n )}%
\n
${sanitizeHTML(\n Yeas\n )}
/\n
${sanitizeHTML(\n Nays\n )}
\n `;\n\n // Voting Buttons for Masternode owners (MNOs)\n let voteBtn;\n if (cProposal.local) {\n const domVoteBtns = domRow.insertCell();\n domVoteBtns.classList.add('for-desktop');\n domVoteBtns.style = 'vertical-align: middle;';\n voteBtn = '';\n } else {\n let btnYesClass = 'pivx-button-small';\n let btnNoClass = 'pivx-button-small';\n if (cProposal.YourVote) {\n if (cProposal.YourVote === 1) {\n btnYesClass += ' pivx-button-big-yes-gov';\n } else {\n btnNoClass += ' pivx-button-big-no-gov';\n }\n }\n const domVoteBtns = domRow.insertCell();\n domVoteBtns.style = 'vertical-align: middle;';\n const domNoBtn = document.createElement('button');\n domNoBtn.className = btnNoClass;\n domNoBtn.innerText = translation.no;\n domNoBtn.onclick = () => govVote(cProposal.Hash, 2);\n\n const domYesBtn = document.createElement('button');\n domYesBtn.className = btnYesClass;\n domYesBtn.innerText = translation.yes;\n domYesBtn.onclick = () => govVote(cProposal.Hash, 1);\n\n // Add border radius to last row\n if (arrProposals.length - 1 == i) {\n domVoteBtns.classList.add('bbrr-7p');\n }\n\n domVoteBtns.classList.add('for-desktop');\n domVoteBtns.appendChild(domNoBtn);\n domVoteBtns.appendChild(domYesBtn);\n\n domNoBtn.setAttribute(\n 'onclick',\n `MPW.govVote('${cProposal.Hash}', 2)`\n );\n domYesBtn.setAttribute(\n 'onclick',\n `MPW.govVote('${cProposal.Hash}', 1);`\n );\n voteBtn = domNoBtn.outerHTML + domYesBtn.outerHTML;\n }\n\n // Create extended row for mobile\n const mobileDomRow = domTable.insertRow();\n const mobileExtended = mobileDomRow.insertCell();\n mobileExtended.style = 'vertical-align: middle;';\n if (domTable.id == 'proposalsTableBody') {\n mobileExtended.id = `governMob${i}`;\n } else if (domTable.id == 'proposalsContestedTableBody') {\n mobileExtended.id = `governMobCon${i}`;\n }\n mobileExtended.colSpan = '2';\n mobileExtended.classList.add('text-left');\n mobileExtended.classList.add('d-none');\n mobileExtended.classList.add('for-mobile');\n mobileExtended.innerHTML = `\n
\n
\n
${translation.govTablePayment}\n
\n
\n ${sanitizeHTML(\n parseInt(cProposal.MonthlyPayment).toLocaleString(\n 'en-gb',\n ',',\n '.'\n )\n )} ${\n cChainParams.current.TICKER\n } ${strProposalCurrency}\n \n ${sanitizeHTML(\n cProposal['RemainingPaymentCount']\n )} ${translation.proposalPaymentsRemaining} ${sanitizeHTML(\n parseInt(cProposal.TotalPayment).toLocaleString('en-gb', ',', '.')\n )} ${cChainParams.current.TICKER} ${\n translation.proposalPaymentTotal\n }\n
\n
\n
\n
\n
\n
${translation.govTableVotes}\n
\n
\n ${parseFloat(nLocalPercent).toLocaleString(\n 'en-gb',\n { minimumFractionDigits: 0, maximumFractionDigits: 1 },\n ',',\n '.'\n )}%\n
${sanitizeHTML(\n Yeas\n )}
/\n
${sanitizeHTML(\n Nays\n )}
\n
\n
\n
\n
\n
\n
${translation.govTableVote}\n
\n
\n ${voteBtn}\n
\n
`;\n\n i++;\n }\n\n // Show allocated budget\n if (domTable.id == 'proposalsTableBody') {\n const strAlloc = sanitizeHTML(\n totalAllocatedAmount.toLocaleString('en-gb')\n );\n doms.domAllocatedGovernanceBudget.innerHTML = strAlloc;\n doms.domAllocatedGovernanceBudget2.innerHTML = strAlloc;\n\n // Update allocated budget in user's currency\n const nCurrencyValue = totalAllocatedAmount * nPrice;\n const { nValue } = optimiseCurrencyLocale(nCurrencyValue);\n const strAllocCurrency =\n nValue.toLocaleString('en-gb', cLocale) +\n ' ' +\n strCurrency.toUpperCase() +\n '';\n doms.domAllocatedGovernanceBudgetValue.innerHTML = strAllocCurrency;\n doms.domAllocatedGovernanceBudgetValue2.innerHTML = strAllocCurrency;\n }\n}\n\nexport async function updateMasternodeTab() {\n //TODO: IN A FUTURE ADD MULTI-MASTERNODE SUPPORT BY SAVING MNs with which you logged in the past.\n // Ensure a wallet is loaded\n doms.domMnTextErrors.innerHTML = '';\n doms.domAccessMasternode.style.display = 'none';\n doms.domCreateMasternode.style.display = 'none';\n doms.domMnDashboard.style.display = 'none';\n\n if (!masterKey) {\n doms.domMnTextErrors.innerHTML =\n 'Please ' +\n ((await hasEncryptedWallet()) ? 'unlock' : 'import') +\n ' your COLLATERAL WALLET first.';\n return;\n }\n\n if (!mempool.getConfirmed().length) {\n doms.domMnTextErrors.innerHTML =\n 'Your wallet is empty or still loading, re-open the tab in a few seconds!';\n return;\n }\n\n const database = await Database.getInstance();\n\n let cMasternode = await database.getMasternode();\n // If the collateral is missing (spent, or switched wallet) then remove the current MN\n if (cMasternode) {\n if (\n !mempool\n .getConfirmed()\n .find((utxo) => isMasternodeUTXO(utxo, cMasternode))\n ) {\n database.removeMasternode();\n cMasternode = null;\n }\n }\n\n doms.domControlMasternode.style.display = cMasternode ? 'block' : 'none';\n\n // first case: the wallet is not HD and it is not hardware, so in case the wallet has collateral the user can check its status and do simple stuff like voting\n if (!masterKey.isHD) {\n doms.domMnAccessMasternodeText.innerHTML =\n doms.masternodeLegacyAccessText;\n doms.domMnTxId.style.display = 'none';\n // Find the first UTXO matching the expected collateral size\n const cCollaUTXO = mempool\n .getConfirmed()\n .find(\n (cUTXO) => cUTXO.sats === cChainParams.current.collateralInSats\n );\n const balance = getBalance(false);\n if (cCollaUTXO) {\n if (cMasternode) {\n await refreshMasternodeData(cMasternode);\n doms.domMnDashboard.style.display = '';\n } else {\n doms.domMnTxId.style.display = 'none';\n doms.domccessMasternode.style.display = 'block';\n }\n } else if (balance < cChainParams.current.collateralInSats) {\n // The user needs more funds\n doms.domMnTextErrors.innerHTML =\n 'You need ' +\n (cChainParams.current.collateralInSats - balance) / COIN +\n ' more ' +\n cChainParams.current.TICKER +\n ' to create a Masternode!';\n } else {\n // The user has the funds, but not an exact collateral, prompt for them to create one\n doms.domCreateMasternode.style.display = 'block';\n doms.domMnTxId.style.display = 'none';\n doms.domMnTxId.innerHTML = '';\n }\n } else {\n doms.domMnTxId.style.display = 'none';\n doms.domMnTxId.innerHTML = '';\n doms.domMnAccessMasternodeText.innerHTML = doms.masternodeHDAccessText;\n\n // First UTXO for each address in HD\n const mapCollateralAddresses = new Map();\n\n // Aggregate all valid Masternode collaterals into a map of Address <--> Collateral\n for (const cUTXO of mempool.getConfirmed()) {\n if (cUTXO.sats !== cChainParams.current.collateralInSats) continue;\n mapCollateralAddresses.set(cUTXO.path, cUTXO);\n }\n const fHasCollateral = mapCollateralAddresses.size > 0;\n\n // If there's no loaded MN, but valid collaterals, display the configuration screen\n if (!cMasternode && fHasCollateral) {\n doms.domMnTxId.style.display = 'block';\n doms.domAccessMasternode.style.display = 'block';\n\n for (const [key] of mapCollateralAddresses) {\n const option = document.createElement('option');\n option.value = key;\n option.innerText = await masterKey.getAddress(key);\n doms.domMnTxId.appendChild(option);\n }\n }\n\n // If there's no collateral found, display the creation UI\n if (!fHasCollateral) doms.domCreateMasternode.style.display = 'block';\n\n // If we have a collateral and a loaded Masternode, display the Dashboard\n if (fHasCollateral && cMasternode) {\n // Refresh the display\n refreshMasternodeData(cMasternode);\n doms.domMnDashboard.style.display = '';\n }\n }\n}\n\nasync function refreshMasternodeData(cMasternode, fAlert = false) {\n const cMasternodeData = await cMasternode.getFullData();\n if (debug) {\n console.log('---- NEW MASTERNODE DATA (Debug Mode) ----');\n console.log(cMasternodeData);\n console.log('---- END MASTERNODE DATA (Debug Mode) ----');\n }\n\n // If we have MN data available, update the dashboard\n if (cMasternodeData && cMasternodeData.status !== 'MISSING') {\n doms.domMnTextErrors.innerHTML = '';\n doms.domMnProtocol.innerText = `(${sanitizeHTML(\n cMasternodeData.version\n )})`;\n doms.domMnStatus.innerText = sanitizeHTML(cMasternodeData.status);\n doms.domMnNetType.innerText = sanitizeHTML(\n cMasternodeData.network.toUpperCase()\n );\n doms.domMnNetIP.innerText = cMasternode.addr;\n doms.domMnLastSeen.innerText = new Date(\n cMasternodeData.lastseen * 1000\n ).toLocaleTimeString();\n }\n\n if (cMasternodeData.status === 'MISSING') {\n doms.domMnTextErrors.innerHTML =\n 'Masternode is currently OFFLINE';\n if (!masterKey.isViewOnly) {\n createAlert('warning', ALERTS.MN_OFFLINE_STARTING, 6000);\n // try to start the masternode\n const started = await cMasternode.start();\n if (started) {\n doms.domMnTextErrors.innerHTML = ALERTS.MN_STARTED;\n createAlert('success', ALERTS.MN_STARTED_ONLINE_SOON, 6000);\n const database = await Database.getInstance();\n await database.addMasternode(cMasternode);\n } else {\n doms.domMnTextErrors.innerHTML = ALERTS.MN_START_FAILED;\n createAlert('warning', ALERTS.MN_START_FAILED, 6000);\n }\n }\n } else if (\n cMasternodeData.status === 'ENABLED' ||\n cMasternodeData.status === 'PRE_ENABLED'\n ) {\n if (fAlert)\n createAlert(\n 'success',\n `${ALERTS.MN_STATUS_IS} ${sanitizeHTML(\n cMasternodeData.status\n )} `,\n 6000\n );\n const database = await Database.getInstance();\n await database.addMasternode(cMasternode);\n } else if (cMasternodeData.status === 'REMOVED') {\n const state = cMasternodeData.status;\n doms.domMnTextErrors.innerHTML = tr(ALERTS.MN_STATE, [\n { state: state },\n ]);\n if (fAlert)\n createAlert(\n 'warning',\n tr(ALERTS.MN_STATE, [{ state: state }]),\n 6000\n );\n } else {\n // connection problem\n doms.domMnTextErrors.innerHTML = ALERTS.MN_CANT_CONNECT;\n if (fAlert) createAlert('warning', ALERTS.MN_CANT_CONNECT, 6000);\n }\n\n // Return the data in case the caller needs additional context\n return cMasternodeData;\n}\n\nexport async function createProposal() {\n if (!masterKey) {\n return createAlert('warning', ALERTS.PROPOSAL_IMPORT_FIRST);\n }\n if (\n masterKey.isViewOnly &&\n !(await restoreWallet(translation.walletUnlockProposal))\n ) {\n return;\n }\n if (getBalance() * COIN < cChainParams.current.proposalFee) {\n return createAlert('warning', ALERTS.PROPOSAL_NOT_ENOUGH_FUNDS);\n }\n\n const fConfirmed = await confirmPopup({\n title: `${translation.popupCreateProposal} (${\n translation.popupCreateProposalCost\n } ${cChainParams.current.proposalFee / COIN} ${\n cChainParams.current.TICKER\n })`,\n html: `
\n
\n
\n
`,\n });\n\n // If the user cancelled, then we return\n if (!fConfirmed) return;\n\n const strTitle = document.getElementById('proposalTitle').value;\n const strUrl = document.getElementById('proposalUrl').value;\n const numCycles = parseInt(document.getElementById('proposalCycles').value);\n const numPayment = parseInt(\n document.getElementById('proposalPayment').value\n );\n const nextSuperblock = await Masternode.getNextSuperblock();\n const proposal = {\n name: strTitle,\n url: strUrl,\n nPayments: numCycles,\n start: nextSuperblock,\n address: (await getNewAddress())[0],\n monthlyPayment: numPayment * COIN,\n };\n\n const isValid = Masternode.isValidProposal(proposal);\n if (!isValid.ok) {\n createAlert(\n 'warning',\n `${ALERTS.PROPOSAL_INVALID_ERROR} ${isValid.err}`,\n 5000\n );\n return;\n }\n\n const hash = Masternode.createProposalHash(proposal);\n const { ok, txid } = await createAndSendTransaction({\n address: hash,\n amount: cChainParams.current.proposalFee,\n isProposal: true,\n });\n if (ok) {\n proposal.txid = txid;\n const database = await Database.getInstance();\n\n // Fetch our Account, add the proposal to it\n const account = await database.getAccount();\n account.localProposals.push(proposal);\n\n // Update the DB\n await database.updateAccount(account);\n createAlert('success', translation.PROPOSAL_CREATED, 7500);\n updateGovernanceTab();\n }\n}\n\nexport function refreshChainData() {\n const cNet = getNetwork();\n // If in offline mode: don't sync ANY data or connect to the internet\n if (!cNet.enabled)\n return console.warn(\n 'Offline mode active: For your security, the wallet will avoid ALL internet requests.'\n );\n if (!masterKey) return;\n\n // Fetch block count + UTXOs, update the UI for new transactions\n cNet.getBlockCount().then((_) => {\n // Fetch latest Activity\n updateActivityGUI(false, true);\n\n // If it's open: update the Governance Dashboard\n if (doms.domGovTab.classList.contains('active')) {\n updateGovernanceTab();\n }\n });\n getBalance(true);\n}\n\n// A safety mechanism enabled if the user attempts to leave without encrypting/saving their keys\nexport const beforeUnloadListener = (evt) => {\n evt.preventDefault();\n // Disable Save your wallet warning on unload\n createAlert('warning', ALERTS.SAVE_WALLET_PLEASE, 10000);\n // Most browsers ignore this nowadays, but still, keep it 'just incase'\n return (evt.returnValue = translation.BACKUP_OR_ENCRYPT_WALLET);\n};\n\n/**\n * @typedef {Object} SettingsDOM - An object that contains the DOM elements for settings pages.\n * @property {HTMLElement} btn - The button to switch to this setting type.\n * @property {HTMLElement} section - The container for this setting type.\n */\n\n/**\n * Returns a list of all pages and their DOM elements.\n *\n * This must be a function, since, the DOM elements are `undefined` until\n * after the startup sequence.\n *\n * Types are inferred.\n */\nfunction getSettingsPages() {\n return {\n /** @type {SettingsDOM} */\n wallet: {\n btn: doms.domWalletSettingsBtn,\n section: doms.domWalletSettings,\n },\n /** @type {SettingsDOM} */\n display: {\n btn: doms.domDisplaySettingsBtn,\n section: doms.domDisplaySettings,\n },\n };\n}\n\n/**\n * Switch between screens in the settings menu\n * @param {string} page - The name of the setting page to switch to\n */\nexport function switchSettings(page) {\n const SETTINGS = getSettingsPages();\n const { btn, section } = SETTINGS[page];\n\n Object.values(SETTINGS).forEach(({ section, btn }) => {\n // Set the slider to the proper location\n if (page == 'display') {\n doms.domDisplayDecimalsSlider.oninput = function () {\n doms.domDisplayDecimalsSliderDisplay.innerHTML = this.value;\n //let val = ((((doms.domDisplayDecimalsSlider.offsetWidth - 24) / 9) ) * parseInt(this.value));\n\n //doms.domDisplayDecimalsSliderDisplay.style.marginLeft = (val) + 'px';\n };\n\n // Triggers the input event\n setTimeout(\n () =>\n doms.domDisplayDecimalsSlider.dispatchEvent(\n new Event('input')\n ),\n 10\n );\n }\n // Hide all settings sections\n section.classList.add('d-none');\n // Make all buttons inactive\n btn.classList.remove('active');\n });\n\n // Show selected section and make its button active\n section.classList.remove('d-none');\n btn.classList.add('active');\n}\n\nfunction errorHandler(e) {\n const message = `${translation.unhandledException}
${sanitizeHTML(\n e.message || e.reason\n )}`;\n try {\n createAlert('warning', message);\n } catch (_) {\n // Something as gone wrong, so we fall back to the default alert\n // This can happen on early errors for example\n alert(message);\n }\n}\n\n// This code is ran in the vanity gen worker as well!\n// In which case, window would be not defined.\n// `if (window)` wouldn't work either because\n// window is not defined as opposed to undefined\ntry {\n window.addEventListener('error', errorHandler);\n window.addEventListener('unhandledrejection', errorHandler);\n} catch (_) {}\n","import { getDerivationPath } from './wallet.js';\nimport { cChainParams, COIN } from './chain_params.js';\nimport { createAlert } from './misc.js';\nimport { Mempool, UTXO } from './mempool.js';\nimport { getEventEmitter } from './event_bus.js';\nimport {\n STATS,\n cStatKeys,\n cAnalyticsLevel,\n setExplorer,\n fAutoSwitch,\n} from './settings.js';\nimport { ALERTS } from './i18n.js';\n\n/**\n * @typedef {Object} XPUBAddress\n * @property {string} type - Type of address (always 'XPUBAddress' for XPUBInfo classes)\n * @property {string} name - PIVX address string\n * @property {string} path - BIP44 path of the address derivation\n * @property {number} transfers - Number of transfers involving the address\n * @property {number} decimals - Decimal places in the amounts (PIVX has 8 decimals)\n * @property {string} balance - Current balance of the address (satoshi)\n * @property {string} totalReceived - Total ever received by the address (satoshi)\n * @property {string} totalSent - Total ever sent from the address (satoshi)\n */\n\n/**\n * @typedef {Object} XPUBInfo\n * @property {number} page - Current response page in a paginated data\n * @property {number} totalPages - Total pages in the paginated data\n * @property {number} itemsOnPage - Number of items on the current page\n * @property {string} address - XPUB string of the address\n * @property {string} balance - Current balance of the xpub (satoshi)\n * @property {string} totalReceived - Total ever received by the xpub (satoshi)\n * @property {string} totalSent - Total ever sent from the xpub (satoshi)\n * @property {string} unconfirmedBalance - Unconfirmed balance of the xpub (satoshi)\n * @property {number} unconfirmedTxs - Number of unconfirmed transactions of the xpub\n * @property {number} txs - Total number of transactions of the xpub\n * @property {string[]?} txids - Transaction ids involving the xpub\n * @property {number?} usedTokens - Number of used token addresses from the xpub\n * @property {XPUBAddress[]?} tokens - Array of used token addresses\n */\n\n/**\n * A historical transaction type.\n * @enum {number}\n */\nexport const HistoricalTxType = {\n UNKNOWN: 0,\n STAKE: 1,\n DELEGATION: 2,\n UNDELEGATION: 3,\n RECEIVED: 4,\n SENT: 5,\n};\n\n/**\n * A historical transaction\n */\nexport class HistoricalTx {\n /**\n * @param {HistoricalTxType} type - The type of transaction.\n * @param {string} id - The transaction ID.\n * @param {Array} senders - The list of 'input addresses'.\n * @param {Array} receivers - The list of 'output addresses'.\n * @param {boolean} shieldedOutputs - If this transaction contains Shield outputs.\n * @param {number} time - The block time of the transaction.\n * @param {number} blockHeight - The block height of the transaction.\n * @param {number} amount - The amount transacted, in coins.\n */\n constructor(\n type,\n id,\n senders,\n receivers,\n shieldedOutputs,\n time,\n blockHeight,\n amount\n ) {\n this.type = type;\n this.id = id;\n this.senders = senders;\n this.receivers = receivers;\n this.shieldedOutputs = shieldedOutputs;\n this.time = time;\n this.blockHeight = blockHeight;\n this.amount = amount;\n }\n}\n\n/**\n * Virtual class rapresenting any network backend\n */\nexport class Network {\n constructor(masterKey) {\n if (this.constructor === Network) {\n throw new Error('Initializing virtual class');\n }\n this._enabled = true;\n\n this.masterKey = masterKey;\n\n this.lastWallet = 0;\n this.isHistorySynced = false;\n }\n\n /**\n * @param {boolean} value\n */\n set enabled(value) {\n if (value !== this._enabled) {\n getEventEmitter().emit('network-toggle', value);\n this._enabled = value;\n }\n }\n\n get enabled() {\n return this._enabled;\n }\n\n enable() {\n this.enabled = true;\n }\n\n disable() {\n this.enabled = false;\n }\n\n toggle() {\n this.enabled = !this.enabled;\n }\n\n getFee(bytes) {\n // TEMPORARY: Hardcoded fee per-byte\n return bytes * 50; // 50 sat/byte\n }\n\n get cachedBlockCount() {\n throw new Error('cachedBlockCount must be implemented');\n }\n\n error() {\n throw new Error('Error must be implemented');\n }\n\n getBlockCount() {\n throw new Error('getBlockCount must be implemented');\n }\n\n sentTransaction() {\n throw new Error('sendTransaction must be implemented');\n }\n\n submitAnalytics(_strType, _cData = {}) {\n throw new Error('submitAnalytics must be implemented');\n }\n\n setMasterKey(masterKey) {\n this.masterKey = masterKey;\n }\n\n async getTxInfo(_txHash) {\n throw new Error('getTxInfo must be implemented');\n }\n}\n\n/**\n *\n */\nexport class ExplorerNetwork extends Network {\n /**\n * @param {string} strUrl - Url pointing to the blockbook explorer\n */\n constructor(strUrl, masterKey) {\n super(masterKey);\n /**\n * @type{string}\n * @public\n */\n this.strUrl = strUrl;\n\n /**\n * @type{Number}\n * @private\n */\n this.blocks = 0;\n\n /**\n * @type {Array}\n */\n this.arrTxHistory = [];\n\n this.historySyncing = false;\n }\n\n error() {\n if (this.enabled) {\n this.disable();\n createAlert('warning', ALERTS.CONNECTION_FAILED);\n }\n }\n\n get cachedBlockCount() {\n return this.blocks;\n }\n\n async getBlockCount() {\n try {\n getEventEmitter().emit('sync-status', 'start');\n const { backend } = await (\n await retryWrapper(fetchBlockbook, `/api/v2/api`)\n ).json();\n if (backend.blocks > this.blocks) {\n console.log(\n 'New block detected! ' +\n this.blocks +\n ' --> ' +\n backend.blocks\n );\n this.blocks = backend.blocks;\n\n await this.getUTXOs();\n }\n } catch (e) {\n this.error();\n throw e;\n } finally {\n getEventEmitter().emit('sync-status', 'stop');\n }\n }\n\n /**\n * @typedef {object} BlockbookUTXO\n * @property {string} txid - The TX hash of the output\n * @property {number} vout - The Index Position of the output\n * @property {string} value - The string-based satoshi value of the output\n * @property {number} height - The block height the TX was confirmed in\n * @property {number} confirmations - The depth of the TX in the blockchain\n */\n\n /**\n * Fetch UTXOs from the current primary explorer\n * @param {string} strAddress - Optional address, gets UTXOs without changing MPW's state\n * @returns {Promise>} Resolves when it has finished fetching UTXOs\n */\n async getUTXOs(strAddress = '') {\n // Don't fetch UTXOs if we're already scanning for them!\n if (!strAddress) {\n if (!this.masterKey) return;\n if (this.isSyncing) return;\n this.isSyncing = true;\n }\n try {\n let publicKey;\n // Derive our XPub, or fetch a single pubkey\n if (this.masterKey.isHD && !strAddress) {\n const derivationPath = getDerivationPath(\n this.masterKey.isHardwareWallet\n )\n .split('/')\n .slice(0, 4)\n .join('/');\n publicKey = await this.masterKey.getxpub(derivationPath);\n } else {\n // Use the param address if specified, or the Master Key by default\n publicKey = strAddress || (await this.masterKey.getAddress());\n }\n\n // Fetch UTXOs for the key\n const arrUTXOs = await (\n await retryWrapper(fetchBlockbook, `/api/v2/utxo/${publicKey}`)\n ).json();\n\n // If using MPW's wallet, then sync the UTXOs in MPW's state\n if (!strAddress) getEventEmitter().emit('utxo', arrUTXOs);\n\n // Return the UTXOs for additional utility use\n return arrUTXOs;\n } catch (e) {\n console.error(e);\n this.error();\n } finally {\n this.isSyncing = false;\n }\n }\n /**\n * Fetches UTXOs full info\n * @param {Object} cUTXO - object-formatted UTXO\n * @returns {Promise} Promise that resolves with the full info of the UTXO\n */\n async getUTXOFullInfo(cUTXO) {\n const cTx = await (\n await retryWrapper(\n fetchBlockbook,\n `/api/v2/tx-specific/${cUTXO.txid}`\n )\n ).json();\n const cVout = cTx.vout[cUTXO.vout];\n\n let path;\n if (cUTXO.path) {\n path = cUTXO.path.split('/');\n path[2] =\n (this.masterKey.isHardwareWallet\n ? cChainParams.current.BIP44_TYPE_LEDGER\n : cChainParams.current.BIP44_TYPE) + \"'\";\n this.lastWallet = Math.max(parseInt(path[5]), this.lastWallet);\n path = path.join('/');\n }\n\n const isColdStake = cVout.scriptPubKey.type === 'coldstake';\n const isStandard = cVout.scriptPubKey.type === 'pubkeyhash';\n const isReward = cTx.vout[0].scriptPubKey.hex === '';\n // We don't know what this is\n if (!isColdStake && !isStandard) {\n return null;\n }\n\n return new UTXO({\n id: cUTXO.txid,\n path,\n sats: Math.round(cVout.value * COIN),\n script: cVout.scriptPubKey.hex,\n vin: cTx?.vin || [],\n vout: cVout.n,\n height: this.cachedBlockCount - (cTx.confirmations - 1),\n status: cTx.confirmations < 1 ? Mempool.PENDING : Mempool.CONFIRMED,\n isDelegate: isColdStake,\n isReward,\n });\n }\n\n /**\n * Fetch an XPub's basic information\n * @param {string} strXPUB - The xpub to fetch info for\n * @returns {Promise} - A JSON class of aggregated XPUB info\n */\n async getXPubInfo(strXPUB) {\n return await (\n await retryWrapper(fetchBlockbook, `/api/v2/xpub/${strXPUB}`)\n ).json();\n }\n\n async sendTransaction(hex) {\n try {\n const data = await (\n await retryWrapper(fetchBlockbook, '/api/v2/sendtx/', {\n method: 'post',\n body: hex,\n })\n ).json();\n\n // Throw and catch if the data is not a TXID\n if (!data.result || data.result.length !== 64) throw data;\n\n console.log('Transaction sent! ' + data.result);\n getEventEmitter().emit('transaction-sent', true, data.result);\n return data.result;\n } catch (e) {\n getEventEmitter().emit('transaction-sent', false, e);\n return false;\n }\n }\n\n /**\n * Synchronise a partial chunk of our TX history\n * @param {boolean} [fNewOnly] - Whether to sync ONLY new transactions\n */\n async syncTxHistoryChunk(fNewOnly = false) {\n // Do not allow multiple calls at once\n if (this.historySyncing) {\n return false;\n }\n try {\n if (!this.enabled || !this.masterKey) return this.arrTxHistory;\n this.historySyncing = true;\n const nHeight = this.arrTxHistory.length\n ? this.arrTxHistory[this.arrTxHistory.length - 1].blockHeight\n : 0;\n const mapPaths = new Map();\n\n // Form the API call using our wallet information\n const fHD = this.masterKey.isHD;\n const strDerivPath = getDerivationPath(\n this.masterKey.isHardwareWallet\n )\n .split('/')\n .slice(0, 4)\n .join('/');\n const strKey = fHD\n ? await this.masterKey.getxpub(strDerivPath)\n : await this.masterKey.getAddress();\n const strRoot = `/api/v2/${fHD ? 'xpub/' : 'address/'}${strKey}`;\n const strCoreParams = `?details=txs&tokens=derived&pageSize=200`;\n const strAPI = strRoot + strCoreParams;\n\n // If we have a known block height, check for incoming transactions within the last 60 blocks\n const cRecentTXs =\n this.blocks > 0\n ? await (\n await retryWrapper(\n fetchBlockbook,\n `${strAPI}&from=${this.blocks - 60}`\n )\n ).json()\n : {};\n\n // If we do not have full history, then load more historical TXs in a slice\n const cData =\n !fNewOnly && !this.isHistorySynced\n ? await (\n await retryWrapper(\n fetchBlockbook,\n `${strAPI}&to=${nHeight ? nHeight - 1 : 0}`\n )\n ).json()\n : {};\n if (fHD && (cData.tokens || cRecentTXs.tokens)) {\n // Map all address <--> derivation paths\n // - From historical transactions\n if (cData.tokens) {\n cData.tokens.forEach((cAddrPath) =>\n mapPaths.set(cAddrPath.name, cAddrPath.path)\n );\n }\n // - From new transactions\n if (cRecentTXs.tokens) {\n cRecentTXs.tokens.forEach((cAddrPath) =>\n mapPaths.set(cAddrPath.name, cAddrPath.path)\n );\n }\n } else {\n mapPaths.set(strKey, ':)');\n }\n\n // Process our aggregated history data\n if (\n (cData && cData.transactions) ||\n (cRecentTXs && cRecentTXs.transactions)\n ) {\n // Process Older (historical) TXs\n const arrOlderTXs = this.toHistoricalTXs(\n cData.transactions || [],\n mapPaths\n );\n\n // Process Recent TXs, then add them manually on the basis that they are NOT already known in history\n const arrRecentTXs = this.toHistoricalTXs(\n cRecentTXs.transactions || [],\n mapPaths\n );\n for (const cTx of arrRecentTXs) {\n if (\n !this.arrTxHistory.find((a) => a.id === cTx.id) &&\n !arrOlderTXs.find((a) => a.id === cTx.id)\n ) {\n // No identical Tx, so prepend it!\n this.arrTxHistory.unshift(cTx);\n }\n }\n this.arrTxHistory = this.arrTxHistory.concat(arrOlderTXs);\n\n // If the results don't match the full 'max/requested results', then we know the history is complete\n if (\n cData.transactions &&\n cData.transactions.length !== cData.itemsOnPage\n ) {\n this.isHistorySynced = true;\n }\n }\n return this.arrTxHistory;\n } catch (e) {\n console.error(e);\n } finally {\n this.historySyncing = false;\n }\n }\n\n /**\n * Convert a list of Blockbook transactions to HistoricalTxs\n * @param {Array} arrTXs - An array of the Blockbook TXs\n * @param {Map} mapPaths - A map of the derivation paths for involved addresses\n * @returns {Array} - A new array of `HistoricalTx`-formatted transactions\n */\n toHistoricalTXs(arrTXs, mapPaths) {\n /**\n * A function to sum a list of inputs (vin) or outputs (vout)\n * @type {(v: Array<{addresses: String[], value: Number}>) => Number}\n */\n const txSum = (v) =>\n v.reduce(\n (t, s) =>\n t +\n (s.addresses &&\n s.addresses.some((strAddr) => mapPaths.has(strAddr))\n ? parseInt(s.value)\n : 0),\n 0\n );\n\n return arrTXs\n .map((tx) => {\n // The total 'delta' or change in balance, from the Tx's sums\n let nAmount = (txSum(tx.vout) - txSum(tx.vin)) / COIN;\n\n // If this Tx creates any Shield outputs\n // Note: shielOuts typo intended, this is a Blockbook error\n const fShieldOuts = Number.isFinite(tx.shielOuts);\n\n // (Un)Delegated coins in this transaction, if any\n let nDelegated = 0;\n\n // The address(es) delegated to, if any\n let strDelegatedAddr = '';\n\n // The sender addresses, if any\n const arrSenders =\n tx.vin?.flatMap((vin) => vin.addresses) || [];\n\n // The receiver addresses, if any\n let arrReceivers =\n tx.vout?.flatMap((vout) => vout.addresses) || [];\n // Pretty-fy script addresses\n arrReceivers = arrReceivers.map((addr) =>\n addr.startsWith('OP_') ? 'Contract' : addr\n );\n\n // Figure out the type, based on the Tx's properties\n let type = HistoricalTxType.UNKNOWN;\n if (\n !fShieldOuts &&\n tx?.vout[0]?.addresses[0]?.startsWith('CoinStake')\n ) {\n type = HistoricalTxType.STAKE;\n } else if (nAmount > 0 || (nAmount > 0 && fShieldOuts)) {\n type = HistoricalTxType.RECEIVED;\n // If this contains Shield outputs, then we received them\n if (fShieldOuts)\n nAmount = parseInt(tx.valueBalanceSat) / COIN;\n } else if (nAmount < 0 || (nAmount < 0 && fShieldOuts)) {\n // Check vins for undelegations\n for (const vin of tx.vin) {\n const fDelegation = vin.addresses?.some((addr) =>\n addr.startsWith(cChainParams.current.STAKING_PREFIX)\n );\n if (fDelegation) {\n nDelegated -= parseInt(vin.value);\n }\n }\n\n // Check vouts for delegations\n for (const out of tx.vout) {\n strDelegatedAddr =\n out.addresses?.find((addr) =>\n addr.startsWith(\n cChainParams.current.STAKING_PREFIX\n )\n ) || strDelegatedAddr;\n\n const fDelegation = !!strDelegatedAddr;\n if (fDelegation) {\n nDelegated += parseInt(out.value);\n }\n }\n\n // If a delegation was made, then display the value delegated\n if (nDelegated > 0) {\n type = HistoricalTxType.DELEGATION;\n nAmount = nDelegated / COIN;\n } else if (nDelegated < 0) {\n type = HistoricalTxType.UNDELEGATION;\n nAmount = nDelegated / COIN;\n } else {\n type = HistoricalTxType.SENT;\n // If this contains Shield outputs, then we sent them\n if (fShieldOuts)\n nAmount = parseInt(tx.valueBalanceSat) / COIN;\n }\n }\n\n return new HistoricalTx(\n type,\n tx.txid,\n arrSenders,\n nDelegated !== 0 ? [strDelegatedAddr] : arrReceivers,\n fShieldOuts,\n tx.blockTime,\n tx.blockHeight,\n Math.abs(nAmount)\n );\n })\n .filter((tx) => tx.amount != 0);\n }\n\n async setMasterKey(masterKey) {\n // If the public Master Key (xpub, address...) is different, then wipe TX history\n if (\n (await this.masterKey?.keyToExport) !==\n (await masterKey?.keyToExport)\n ) {\n this.arrTxHistory = [];\n }\n\n // Set the key\n this.masterKey = masterKey;\n }\n\n async getTxInfo(txHash) {\n const req = await retryWrapper(fetchBlockbook, `/api/v2/tx/${txHash}`);\n return await req.json();\n }\n\n // PIVX Labs Analytics: if you are a user, you can disable this FULLY via the Settings.\n // ... if you're a developer, we ask you to keep these stats to enhance upstream development,\n // ... but you are free to completely strip MPW of any analytics, if you wish, no hard feelings.\n submitAnalytics(strType, cData = {}) {\n if (!this.enabled) return;\n\n // TODO: rebuild Labs Analytics, submitAnalytics() will be disabled at code-level until this is live again\n /* eslint-disable */\n return;\n\n // Limit analytics here to prevent 'leakage' even if stats are implemented incorrectly or forced\n let i = 0,\n arrAllowedKeys = [];\n for (i; i < cAnalyticsLevel.stats.length; i++) {\n const cStat = cAnalyticsLevel.stats[i];\n arrAllowedKeys.push(cStatKeys.find((a) => STATS[a] === cStat));\n }\n\n // Check if this 'stat type' was granted permissions\n if (!arrAllowedKeys.includes(strType)) return false;\n\n // Format\n const cStats = { type: strType, ...cData };\n\n // Send to Labs Analytics\n const request = new XMLHttpRequest();\n request.open('POST', 'https://scpscan.net/mpw/statistic', true);\n request.setRequestHeader('Content-Type', 'application/json');\n request.send(JSON.stringify(cStats));\n return true;\n }\n}\n\nlet _network = null;\n\n/**\n * Sets the network in use by MPW.\n * @param {ExplorerNetwork} network - network to use\n */\nexport function setNetwork(network) {\n _network = network;\n}\n\n/**\n * Gets the network in use by MPW.\n * @returns {ExplorerNetwork?} Returns the network in use, may be null if MPW hasn't properly loaded yet.\n */\nexport function getNetwork() {\n return _network;\n}\n\n/**\n * A Fetch wrapper which uses the current Blockbook Network's base URL\n * @param {string} api - The specific Blockbook api to call\n * @param {RequestInit} options - The Fetch options\n * @returns {Promise} - The unresolved Fetch promise\n */\nexport function fetchBlockbook(api, options) {\n return fetch(_network.strUrl + api, options);\n}\n\n/**\n * A wrapper for Blockbook calls which can, in the event of an unresponsive explorer,\n * seamlessly attempt the same call on multiple other explorers until success.\n * @param {Function} func - The function to re-attempt with\n * @param {...any} args - The arguments to pass to the function\n */\nasync function retryWrapper(func, ...args) {\n // Track internal errors from the wrapper\n let err;\n\n // If allowed by the user, Max Tries is ALL MPW-supported explorers, otherwise, restrict to only the current one.\n let nMaxTries = cChainParams.current.Explorers.length;\n let retries = 0;\n\n // The explorer index we started at\n let nIndex = cChainParams.current.Explorers.findIndex(\n (a) => a.url === getNetwork().strUrl\n );\n\n // Run the call until successful, or all attempts exhausted\n while (retries < nMaxTries) {\n try {\n // Call the passed function with the arguments\n const res = await func(...args);\n\n // If the endpoint is non-OK, assume it's an error\n if (!res.ok) throw res;\n\n // Return the result if successful\n return res;\n } catch (error) {\n err = error;\n\n // If allowed, switch explorers\n if (!fAutoSwitch) throw err;\n nIndex = (nIndex + 1) % cChainParams.current.Explorers.length;\n const cNewExplorer = cChainParams.current.Explorers[nIndex];\n\n // Set the explorer at Network-class level, then as a hacky workaround for the current callback; we\n // ... adjust the internal URL to the new explorer.\n getNetwork().strUrl = cNewExplorer.url;\n setExplorer(cNewExplorer, true);\n\n // Bump the attempts, and re-try next loop\n retries++;\n }\n }\n\n // Throw an error so the calling code knows the operation failed\n throw err;\n}\n","const buff_to_base64 = (buff) => btoa(String.fromCharCode.apply(null, buff));\n\nconst base64_to_buf = (b64) =>\n Uint8Array.from(atob(b64), (c) => c.charCodeAt(null));\n\nconst enc = new TextEncoder();\nconst dec = new TextDecoder();\n\nexport async function encrypt(data, strPassword = '') {\n const strPass =\n strPassword ||\n window.prompt('Please enter your wallet encryption password');\n if (!strPass) return false;\n return await encryptData(data, strPass);\n}\n\nexport async function decrypt(data, strPassword) {\n const strPass =\n strPassword ||\n window.prompt('Please enter your wallet unlock password');\n if (!strPass) return false;\n return (await decryptData(data, strPass)) || 'decryption failed!';\n}\n\nconst getPasswordKey = (password) =>\n window.crypto.subtle.importKey(\n 'raw',\n enc.encode(password),\n 'PBKDF2',\n false,\n ['deriveKey']\n );\n\nconst deriveKey = (passwordKey, salt, keyUsage) =>\n window.crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt,\n iterations: 250000,\n hash: 'SHA-256',\n },\n passwordKey,\n { name: 'AES-GCM', length: 256 },\n false,\n keyUsage\n );\n\nasync function encryptData(secretData, password) {\n try {\n const salt = window.crypto.getRandomValues(new Uint8Array(16));\n const iv = window.crypto.getRandomValues(new Uint8Array(12));\n const passwordKey = await getPasswordKey(password);\n const aesKey = await deriveKey(passwordKey, salt, ['encrypt']);\n const encryptedContent = await window.crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv: iv,\n },\n aesKey,\n enc.encode(secretData)\n );\n\n const encryptedContentArr = new Uint8Array(encryptedContent);\n let buff = new Uint8Array(\n salt.byteLength + iv.byteLength + encryptedContentArr.byteLength\n );\n buff.set(salt, 0);\n buff.set(iv, salt.byteLength);\n buff.set(encryptedContentArr, salt.byteLength + iv.byteLength);\n return buff_to_base64(buff);\n } catch (e) {\n console.log(`Error - ${e}`);\n return '';\n }\n}\n\nasync function decryptData(encryptedData, password) {\n try {\n const encryptedDataBuff = base64_to_buf(encryptedData);\n const salt = encryptedDataBuff.slice(0, 16);\n const iv = encryptedDataBuff.slice(16, 16 + 12);\n const data = encryptedDataBuff.slice(16 + 12);\n const passwordKey = await getPasswordKey(password);\n const aesKey = await deriveKey(passwordKey, salt, ['decrypt']);\n const decryptedContent = await window.crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: iv,\n },\n aesKey,\n data\n );\n return dec.decode(decryptedContent);\n } catch (e) {\n console.log(`Error - ${e}`);\n return '';\n }\n}\n","import { hexToBytes, bytesToHex, dSHA256 } from './utils.js';\nimport * as nobleSecp256k1 from '@noble/secp256k1';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { ripemd160 } from '@noble/hashes/ripemd160';\nimport { generateMnemonic, mnemonicToSeed, validateMnemonic } from 'bip39';\nimport { doms, beforeUnloadListener } from './global.js';\nimport HDKey from 'hdkey';\nimport { getNetwork } from './network.js';\nimport {\n pubKeyHashNetworkLen,\n confirmPopup,\n writeToUint8,\n pubPrebaseLen,\n createAlert,\n sleep,\n getSafeRand,\n isXPub,\n isStandardAddress,\n} from './misc.js';\nimport {\n refreshChainData,\n setDisplayForAllWalletOptions,\n getBalance,\n getStakingBalance,\n} from './global.js';\nimport {\n cChainParams,\n MAX_ACCOUNT_GAP,\n PRIVKEY_BYTE_LENGTH,\n} from './chain_params.js';\nimport { ALERTS, tr, translation } from './i18n.js';\nimport { encrypt, decrypt } from './aes-gcm.js';\nimport bs58 from 'bs58';\nimport AppBtc from '@ledgerhq/hw-app-btc';\nimport TransportWebUSB from '@ledgerhq/hw-transport-webusb';\nimport createXpub from 'create-xpub';\nimport * as jdenticon from 'jdenticon';\nimport { Database } from './database.js';\nimport { guiRenderCurrentReceiveModal } from './contacts-book.js';\nimport { Account } from './accounts.js';\nimport { debug, fAdvancedMode } from './settings.js';\n\nexport let fWalletLoaded = false;\n\n/**\n * Abstract class masterkey\n * @abstract\n */\nclass MasterKey {\n #addressIndex = 0;\n /**\n * Map our own address -> Path\n * @type {Map}\n */\n #ownAddresses = new Map();\n\n constructor() {\n if (this.constructor === MasterKey) {\n throw new Error('initializing virtual class');\n }\n }\n\n /**\n * @param {String} [path] - BIP32 path pointing to the private key.\n * @return {Promise>} Array of bytes containing private key\n * @abstract\n */\n async getPrivateKeyBytes(_path) {\n throw new Error('Not implemented');\n }\n\n /**\n * @param {String} [path] - BIP32 path pointing to the private key.\n * @return {Promise} encoded private key\n * @abstract\n */\n async getPrivateKey(path) {\n return generateOrEncodePrivkey(await this.getPrivateKeyBytes(path))\n .strWIF;\n }\n\n /**\n * @param {String} [path] - BIP32 path pointing to the address\n * @return {Promise} Address\n * @abstract\n */\n async getAddress(path) {\n return deriveAddress({ pkBytes: await this.getPrivateKeyBytes(path) });\n }\n\n /**\n * @param {String} path - BIP32 path pointing to the xpub\n * @return {Promise} xpub\n * @abstract\n */\n async getxpub(_path) {\n throw new Error('Not implemented');\n }\n\n /**\n * Wipe all private data from key.\n * @return {void}\n * @abstract\n */\n wipePrivateData() {\n throw new Error('Not implemented');\n }\n\n /**\n * @return {String} private key suitable for backup.\n * @abstract\n */\n get keyToBackup() {\n throw new Error('Not implemented');\n }\n\n /**\n * @return {Promise} public key to export. Only suitable for monitoring balance.\n * @abstract\n */\n get keyToExport() {\n throw new Error('Not implemented');\n }\n\n /**\n * @return {Boolean} Whether or not this is a Hierarchical Deterministic wallet\n */\n get isHD() {\n return this._isHD;\n }\n\n /**\n * @return {Boolean} Whether or not this is a hardware wallet\n */\n get isHardwareWallet() {\n return this._isHardwareWallet;\n }\n\n /**\n * @return {Boolean} Whether or not this key is view only or not\n */\n get isViewOnly() {\n return this._isViewOnly;\n }\n\n /**\n * @param {string} address - address to check\n * @return {Promise} BIP32 path or null if it's not your address\n */\n async isOwnAddress(address) {\n if (this.#ownAddresses.has(address)) {\n return this.#ownAddresses.get(address);\n }\n const last = getNetwork().lastWallet;\n this.#addressIndex =\n this.#addressIndex > last ? this.#addressIndex : last;\n if (this.isHD) {\n for (let i = 0; i < this.#addressIndex; i++) {\n const path = getDerivationPath(this.isHardwareWallet, 0, 0, i);\n const testAddress = await masterKey.getAddress(path);\n if (address === testAddress) {\n this.#ownAddresses.set(address, path);\n return path;\n }\n }\n } else {\n const value = address === (await this.keyToExport) ? ':)' : null;\n this.#ownAddresses.set(address, value);\n return value;\n }\n\n this.#ownAddresses.set(address, null);\n return null;\n }\n\n /**\n * @return Promise<[string, string]> Address and its BIP32 derivation path\n */\n async getNewAddress() {\n const last = getNetwork().lastWallet;\n this.#addressIndex =\n (this.#addressIndex > last ? this.#addressIndex : last) + 1;\n if (this.#addressIndex - last > MAX_ACCOUNT_GAP) {\n // If the user creates more than ${MAX_ACCOUNT_GAP} empty wallets we will not be able to sync them!\n this.#addressIndex = last;\n }\n const path = getDerivationPath(\n this.isHardwareWallet,\n 0,\n 0,\n this.#addressIndex\n );\n const address = await this.getAddress(path);\n return [address, path];\n }\n\n /**\n * Derive the current address (by internal index)\n * @return {Promise} Address\n * @abstract\n */\n async getCurrentAddress() {\n return await this.getAddress(\n getDerivationPath(this.isHardwareWallet, 0, 0, this.#addressIndex)\n );\n }\n}\n\nexport class HdMasterKey extends MasterKey {\n constructor({ seed, xpriv, xpub }) {\n super();\n // Generate the HDKey\n if (seed) this._hdKey = HDKey.fromMasterSeed(seed);\n if (xpriv) this._hdKey = HDKey.fromExtendedKey(xpriv);\n if (xpub) this._hdKey = HDKey.fromExtendedKey(xpub);\n this._isViewOnly = !!xpub;\n if (!this._hdKey)\n throw new Error('All of seed, xpriv and xpub are undefined');\n this._isHD = true;\n this._isHardwareWallet = false;\n }\n\n async getPrivateKeyBytes(path) {\n if (this.isViewOnly) {\n throw new Error(\n 'Trying to get private key bytes from a view only key'\n );\n }\n return this._hdKey.derive(path).privateKey;\n }\n\n get keyToBackup() {\n if (this.isViewOnly) {\n throw new Error('Trying to get private key from a view only key');\n }\n return this._hdKey.privateExtendedKey;\n }\n\n async getxpub(path) {\n if (this.isViewOnly) return this._hdKey.publicExtendedKey;\n return this._hdKey.derive(path).publicExtendedKey;\n }\n\n getAddress(path) {\n let child;\n if (this.isViewOnly) {\n // If we're view only we can't derive hardened keys, so we'll assume\n // That the xpub has already been derived\n child = this._hdKey.derive(\n path\n .split('/')\n .filter((n) => !n.includes(\"'\"))\n .join('/')\n );\n } else {\n child = this._hdKey.derive(path);\n }\n return deriveAddress({ publicKey: bytesToHex(child.publicKey) });\n }\n\n wipePrivateData() {\n if (this._isViewOnly) return;\n\n this._hdKey = HDKey.fromExtendedKey(this.keyToExport);\n this._isViewOnly = true;\n }\n\n get keyToExport() {\n if (this._isViewOnly) return this._hdKey.publicExtendedKey;\n // We need the xpub to point at the account level\n return this._hdKey.derive(\n getDerivationPath(false, 0, 0, 0, false)\n .split('/')\n .slice(0, 4)\n .join('/')\n ).publicExtendedKey;\n }\n}\n\nexport class HardwareWalletMasterKey extends MasterKey {\n constructor() {\n super();\n this._isHD = true;\n this._isHardwareWallet = true;\n }\n async getPrivateKeyBytes(_path) {\n throw new Error('Hardware wallets cannot export private keys');\n }\n\n async getAddress(path, { verify } = {}) {\n return deriveAddress({\n publicKey: await this.getPublicKey(path, { verify }),\n });\n }\n\n async getPublicKey(path, { verify } = {}) {\n return deriveAddress({\n publicKey: await getHardwareWalletKeys(path, false, verify),\n output: 'COMPRESSED_HEX',\n });\n }\n\n get keyToBackup() {\n throw new Error(\"Hardware wallets don't have keys to backup\");\n }\n\n async getxpub(path) {\n if (!this.xpub) {\n this.xpub = await getHardwareWalletKeys(path, true);\n }\n return this.xpub;\n }\n\n // Hardware Wallets don't have exposed private data\n wipePrivateData() {}\n\n get isViewOnly() {\n return false;\n }\n get keyToExport() {\n const derivationPath = getDerivationPath(masterKey.isHardwareWallet)\n .split('/')\n .slice(0, 4)\n .join('/');\n return this.getxpub(derivationPath);\n }\n}\n\nexport class LegacyMasterKey extends MasterKey {\n constructor({ pkBytes, address }) {\n super();\n this._isHD = false;\n this._isHardwareWallet = false;\n this._pkBytes = pkBytes;\n this._address = address || super.getAddress();\n this._isViewOnly = !!address;\n }\n\n getAddress() {\n return this._address;\n }\n\n get keyToExport() {\n return this._address;\n }\n\n async getPrivateKeyBytes(_path) {\n if (this.isViewOnly) {\n throw new Error(\n 'Trying to get private key bytes from a view only key'\n );\n }\n return this._pkBytes;\n }\n\n get keyToBackup() {\n return generateOrEncodePrivkey(this._pkBytes).strWIF;\n }\n\n async getxpub(_path) {\n throw new Error(\n 'Trying to get an extended public key from a legacy address'\n );\n }\n\n wipePrivateData() {\n this._pkBytes = null;\n this._isViewOnly = true;\n }\n}\n\n// Ledger Hardware wallet constants\nexport const LEDGER_ERRS = new Map([\n // Ledger error code <--> User-friendly string\n [25870, 'Open the PIVX app on your device'],\n [25873, 'Open the PIVX app on your device'],\n [57408, 'Navigate to the PIVX app on your device'],\n [27157, 'Wrong app! Open the PIVX app on your device'],\n [27266, 'Wrong app! Open the PIVX app on your device'],\n [27904, 'Wrong app! Open the PIVX app on your device'],\n [27010, 'Unlock your Ledger, then try again!'],\n [27404, 'Unlock your Ledger, then try again!'],\n]);\n\n/**\n * @type{MasterKey}\n */\nexport let masterKey;\n\n// Construct a full BIP44 pubkey derivation path from it's parts\nexport function getDerivationPath(\n fLedger = false,\n nAccount = 0,\n nReceiving = 0,\n nIndex = 0,\n /**\n * When `true` will derive based on local wallet properties, when `false` it\n * will default to only accept given params and ignore the local configuration\n * @type {boolean}\n */\n fLocalWallet = true\n) {\n // Coin-Type is different on Ledger, as such, for local wallets; we modify it if we're using a Ledger to derive a key\n const strCoinType =\n fLocalWallet && fLedger\n ? cChainParams.current.BIP44_TYPE_LEDGER\n : cChainParams.current.BIP44_TYPE;\n if (fLocalWallet && masterKey && !masterKey.isHD && !fLedger) {\n return `:)//${strCoinType}'`;\n }\n return `m/44'/${strCoinType}'/${nAccount}'/${nReceiving}/${nIndex}`;\n}\n\n// Verify the integrity of a WIF private key, optionally parsing and returning the key payload\nexport function verifyWIF(\n strWIF = '',\n fParseBytes = false,\n skipVerification = false\n) {\n // Convert from Base58\n const bWIF = bs58.decode(strWIF);\n\n if (!skipVerification) {\n // Verify the byte length\n if (bWIF.byteLength !== PRIVKEY_BYTE_LENGTH) {\n throw Error(\n 'Private key length (' +\n bWIF.byteLength +\n ') is invalid, should be ' +\n PRIVKEY_BYTE_LENGTH +\n '!'\n );\n }\n\n // Verify the network byte\n if (bWIF[0] !== cChainParams.current.SECRET_KEY) {\n // Find the network it's trying to use, if any\n const cNetwork = Object.keys(cChainParams)\n .filter((strNet) => strNet !== 'current')\n .map((strNet) => cChainParams[strNet])\n .find((cNet) => cNet.SECRET_KEY === bWIF[0]);\n // Give a specific alert based on the byte properties\n throw Error(\n cNetwork\n ? 'This private key is for ' +\n (cNetwork.isTestnet ? 'Testnet' : 'Mainnet') +\n ', wrong network!'\n : 'This private key belongs to another coin, or is corrupted.'\n );\n }\n\n // Perform SHA256d hash of the WIF bytes\n const shaHash = dSHA256(bWIF.slice(0, 34));\n\n // Verify checksum (comparison by String since JS hates comparing object-like primitives)\n const bChecksumWIF = bWIF.slice(bWIF.byteLength - 4);\n const bChecksum = shaHash.slice(0, 4);\n if (bChecksumWIF.join('') !== bChecksum.join('')) {\n throw Error(\n 'Private key checksum is invalid, key may be modified, mis-typed, or corrupt.'\n );\n }\n }\n\n return fParseBytes ? Uint8Array.from(bWIF.slice(1, 33)) : true;\n}\n\n// A convenient alias to verifyWIF that returns the raw byte payload\nexport function parseWIF(strWIF, skipVerification = false) {\n return verifyWIF(strWIF, true, skipVerification);\n}\n\n/**\n * Private key in Bytes and WIF formats\n * @typedef {Object} PrivateKey\n * @property {Uint8Array} pkBytes - The unprocessed Private Key bytes.\n * @property {string} strWIF - The WIF encoded private key string.\n */\n\n/**\n * Network encode 32 bytes for a private key\n * @param {Uint8Array} pkBytes - 32 Bytes\n * @returns {Uint8Array} - The network-encoded Private Key bytes\n */\nexport function encodePrivkeyBytes(pkBytes) {\n const pkNetBytes = new Uint8Array(pkBytes.length + 2);\n pkNetBytes[0] = cChainParams.current.SECRET_KEY; // Private key prefix (1 byte)\n writeToUint8(pkNetBytes, pkBytes, 1); // Private key bytes (32 bytes)\n pkNetBytes[pkNetBytes.length - 1] = 1; // Leading digit (1 byte)\n return pkNetBytes;\n}\n\n/**\n * Generate a new private key OR encode an existing private key from raw bytes\n * @param {Uint8Array} pkBytesToEncode - Bytes to encode as a coin private key\n * @returns {PrivateKey} - The private key\n */\nexport function generateOrEncodePrivkey(pkBytesToEncode) {\n // Private Key Generation\n const pkBytes = pkBytesToEncode || getSafeRand();\n\n // Network Encoding\n const pkNetBytes = encodePrivkeyBytes(pkBytes);\n\n // Double SHA-256 hash\n const shaObj = dSHA256(pkNetBytes);\n\n // WIF Checksum\n const checksum = shaObj.slice(0, 4);\n const keyWithChecksum = new Uint8Array(34 + checksum.length);\n writeToUint8(keyWithChecksum, pkNetBytes, 0);\n writeToUint8(keyWithChecksum, checksum, 34);\n\n // Return both the raw bytes and the WIF format\n return { pkBytes, strWIF: bs58.encode(keyWithChecksum) };\n}\n\n/**\n * Compress an uncompressed Public Key in byte form\n * @param {Array | Uint8Array} pubKeyBytes - The uncompressed public key bytes\n * @returns {Array} The compressed public key bytes\n */\nfunction compressPublicKey(pubKeyBytes) {\n if (pubKeyBytes.length != 65)\n throw new Error('Attempting to compress an invalid uncompressed key');\n const x = pubKeyBytes.slice(1, 33);\n const y = pubKeyBytes.slice(33);\n\n // Compressed key is [key_parity + 2, x]\n return [y[31] % 2 === 0 ? 2 : 3, ...x];\n}\n\n/**\n * Derive a Secp256k1 network-encoded public key (coin address) from raw private or public key bytes\n * @param {Object} options - The object to deconstruct\n * @param {String} [options.publicKey] - The hex encoded public key. Can be both compressed or uncompressed\n * @param {Array | Uint8Array} [options.pkBytes] - An array of bytes containing the private key\n * @param {\"ENCODED\" | \"UNCOMPRESSED_HEX\" | \"COMPRESSED_HEX\"} options.output - Output\n * @return {String} the public key with the specified encoding\n */\nexport function deriveAddress({ pkBytes, publicKey, output = 'ENCODED' }) {\n if (!pkBytes && !publicKey) return null;\n const compress = output !== 'UNCOMPRESSED_HEX';\n // Public Key Derivation\n let pubKeyBytes = publicKey\n ? hexToBytes(publicKey)\n : nobleSecp256k1.getPublicKey(pkBytes, compress);\n\n if (output === 'UNCOMPRESSED_HEX') {\n if (pubKeyBytes.length !== 65) {\n // It's actually possible, but it's probably not something that we'll need\n throw new Error(\"Can't uncompress an already compressed key\");\n }\n return bytesToHex(pubKeyBytes);\n }\n\n if (pubKeyBytes.length === 65) {\n pubKeyBytes = compressPublicKey(pubKeyBytes);\n }\n\n if (pubKeyBytes.length != 33) {\n throw new Error('Invalid public key');\n }\n\n if (output === 'COMPRESSED_HEX') {\n return bytesToHex(pubKeyBytes);\n }\n\n // First pubkey SHA-256 hash\n const pubKeyHashing = sha256(new Uint8Array(pubKeyBytes));\n\n // RIPEMD160 hash\n const pubKeyHashRipemd160 = ripemd160(pubKeyHashing);\n\n // Network Encoding\n const pubKeyHashNetwork = new Uint8Array(pubKeyHashNetworkLen);\n pubKeyHashNetwork[0] = cChainParams.current.PUBKEY_ADDRESS;\n writeToUint8(pubKeyHashNetwork, pubKeyHashRipemd160, 1);\n\n // Double SHA-256 hash\n const pubKeyHashingSF = dSHA256(pubKeyHashNetwork);\n\n // Checksum\n const checksumPubKey = pubKeyHashingSF.slice(0, 4);\n\n // Public key pre-base58\n const pubKeyPreBase = new Uint8Array(pubPrebaseLen);\n writeToUint8(pubKeyPreBase, pubKeyHashNetwork, 0);\n writeToUint8(pubKeyPreBase, checksumPubKey, pubKeyHashNetworkLen);\n\n // Encode as Base58 human-readable network address\n return bs58.encode(pubKeyPreBase);\n}\n\n/**\n * Import a wallet (with it's private, public or encrypted data)\n * @param {object} options\n * @param {string | Array} options.newWif - The import data (if omitted, the UI input is accessed)\n * @param {boolean} options.fRaw - Whether the import data is raw bytes or encoded (WIF, xpriv, seed)\n * @param {boolean} options.isHardwareWallet - Whether the import is from a Hardware wallet or not\n * @param {boolean} options.fSavePublicKey - Whether to save the derived public key to disk (for View Only mode)\n * @param {boolean} options.fStartup - Whether the import is at Startup or at Runtime\n * @returns {Promise}\n */\nexport async function importWallet({\n newWif = false,\n fRaw = false,\n isHardwareWallet = false,\n fSavePublicKey = false,\n fStartup = false,\n} = {}) {\n // TODO: remove `walletConfirm`, it is useless as Accounts cannot be overriden, and multi-accounts will come soon anyway\n // ... just didn't want to add a huge whitespace change from removing the `if (walletConfirm) {` line\n const walletConfirm = true;\n if (walletConfirm) {\n if (isHardwareWallet) {\n // Firefox does NOT support WebUSB, thus cannot work with Hardware wallets out-of-the-box\n if (navigator.userAgent.includes('Firefox')) {\n return createAlert(\n 'warning',\n ALERTS.WALLET_FIREFOX_UNSUPPORTED,\n 7500\n );\n }\n const publicKey = await getHardwareWalletKeys(\n getDerivationPath(true)\n );\n // Errors are handled within the above function, so there's no need for an 'else' here, just silent ignore.\n if (!publicKey) return;\n\n // Derive our hardware address and import!\n await setMasterKey(new HardwareWalletMasterKey());\n\n // Hide the 'export wallet' button, it's not relevant to hardware wallets\n doms.domExportWallet.hidden = true;\n\n createAlert(\n 'info',\n tr(ALERTS.WALLET_HARDWARE_WALLET, [\n { hardwareWallet: strHardwareName },\n ]),\n 12500\n );\n } else {\n // If raw bytes: purely encode the given bytes rather than generating our own bytes\n if (fRaw) {\n newWif = generateOrEncodePrivkey(newWif).strWIF;\n\n // A raw import likely means non-user owned key (i.e: created via VanityGen), thus, we assume safety first and add an exit blocking listener\n addEventListener('beforeunload', beforeUnloadListener, {\n capture: true,\n });\n }\n\n // Select WIF from internal source OR user input (could be: WIF, Mnemonic or xpriv)\n const privateImportValue = newWif || doms.domPrivKey.value;\n const passphrase = doms.domPrivKeyPassword.value;\n doms.domPrivKey.value = '';\n doms.domPrivKeyPassword.value = '';\n\n // Clean and verify the Seed Phrase (if one exists)\n const cPhraseValidator = await cleanAndVerifySeedPhrase(\n privateImportValue,\n true\n );\n\n // If Debugging is enabled, show what the validator returned\n if (debug) {\n const fnLog = cPhraseValidator.ok ? console.log : console.warn;\n fnLog('Seed Import Validator: ' + cPhraseValidator.msg);\n }\n\n // If the Seed is OK, proceed\n if (cPhraseValidator.ok) {\n // Generate our HD MasterKey with the cleaned (Mnemonic) Seed Phrase\n const seed = await mnemonicToSeed(\n cPhraseValidator.phrase,\n passphrase\n );\n await setMasterKey(new HdMasterKey({ seed }));\n } else if (cPhraseValidator.phrase.includes(' ')) {\n // The Phrase Validator failed, but the input contains at least one space; possibly a Seed Typo?\n return createAlert('warning', cPhraseValidator.msg, 5000);\n } else {\n // The input definitely isn't a seed, so we'll try every other import method\n try {\n // XPub import (HD view only)\n if (isXPub(privateImportValue)) {\n await setMasterKey(\n new HdMasterKey({\n xpub: privateImportValue,\n })\n );\n // XPrv import (HD full access)\n } else if (privateImportValue.startsWith('xprv')) {\n await setMasterKey(\n new HdMasterKey({\n xpriv: privateImportValue,\n })\n );\n // Pubkey import (non-HD view only)\n } else if (isStandardAddress(privateImportValue)) {\n await setMasterKey(\n new LegacyMasterKey({\n address: privateImportValue,\n })\n );\n // WIF import (non-HD full access)\n } else {\n // Attempt to import a raw WIF private key\n const pkBytes = parseWIF(privateImportValue);\n await setMasterKey(new LegacyMasterKey({ pkBytes }));\n }\n } catch (e) {\n return createAlert(\n 'warning',\n ALERTS.FAILED_TO_IMPORT + '
' + e.message,\n 6000\n );\n }\n }\n }\n\n // Reaching here: the deserialisation was a full cryptographic success, so a wallet is now imported!\n fWalletLoaded = true;\n\n // Hide wipe wallet button if there is no private key\n if (masterKey.isViewOnly || masterKey.isHardwareWallet) {\n doms.domWipeWallet.hidden = true;\n if (await hasEncryptedWallet()) {\n doms.domRestoreWallet.hidden = false;\n }\n }\n\n // For non-HD wallets: hide the 'new address' button, since these are essentially single-address MPW wallets\n if (!masterKey.isHD) doms.domNewAddress.style.display = 'none';\n\n // Update the loaded address in the Dashboard\n getNewAddress({ updateGUI: true });\n\n // Display Text\n doms.domGuiWallet.style.display = 'block';\n doms.domDashboard.click();\n\n // Update identicon\n doms.domIdenticon.dataset.jdenticonValue = masterKey.getAddress(\n getDerivationPath()\n );\n jdenticon.update('#identicon');\n\n // Hide the encryption prompt if the user is using\n // a hardware wallet, or is view-only mode.\n if (!(isHardwareWallet || masterKey.isViewOnly)) {\n if (\n // If the wallet was internally imported (not UI pasted), like via vanity, display the encryption prompt\n (((fRaw && newWif.length) || newWif) &&\n !(await hasEncryptedWallet())) ||\n // If the wallet was pasted and is an unencrypted key, then display the encryption prompt\n !(await hasEncryptedWallet())\n ) {\n doms.domGenKeyWarning.style.display = 'block';\n } else if (await hasEncryptedWallet()) {\n // If the wallet was pasted and is an encrypted import, display the lock wallet UI\n doms.domWipeWallet.hidden = false;\n }\n } else {\n // Hide the encryption UI\n doms.domGenKeyWarning.style.display = 'none';\n }\n\n // Fetch state from explorer, if this import was post-startup\n if (getNetwork().enabled && !fStartup) {\n refreshChainData();\n getNetwork().getUTXOs();\n }\n\n // Hide all wallet starter options\n setDisplayForAllWalletOptions('none');\n }\n}\n\n/**\n * Set or replace the active Master Key with a new Master Key\n * @param {MasterKey} mk - The new Master Key to set active\n */\nexport async function setMasterKey(mk) {\n masterKey = mk;\n // Update the network master key\n await getNetwork().setMasterKey(masterKey);\n}\n\n// Wallet Generation\nexport async function generateWallet(noUI = false) {\n // TODO: remove `walletConfirm`, it is useless as Accounts cannot be overriden, and multi-accounts will come soon anyway\n // ... just didn't want to add a huge whitespace change from removing the `if (walletConfirm) {` line\n const walletConfirm = true;\n if (walletConfirm) {\n const mnemonic = generateMnemonic();\n\n const passphrase = !noUI\n ? await informUserOfMnemonic(mnemonic)\n : undefined;\n const seed = await mnemonicToSeed(mnemonic, passphrase);\n\n // Prompt the user to encrypt the seed\n await setMasterKey(new HdMasterKey({ seed }));\n fWalletLoaded = true;\n\n doms.domGenKeyWarning.style.display = 'block';\n // Add a listener to block page unloads until we are sure the user has saved their keys, safety first!\n addEventListener('beforeunload', beforeUnloadListener, {\n capture: true,\n });\n\n // Display the dashboard\n doms.domGuiWallet.style.display = 'block';\n setDisplayForAllWalletOptions('none');\n\n // Update identicon\n doms.domIdenticon.dataset.jdenticonValue = masterKey.getAddress(\n getDerivationPath()\n );\n jdenticon.update('#identicon');\n\n getNewAddress({ updateGUI: true });\n\n // Refresh the balance UI (why? because it'll also display any 'get some funds!' alerts)\n getBalance(true);\n getStakingBalance(true);\n }\n\n return masterKey;\n}\n\n/**\n * Clean a Seed Phrase string and verify it's integrity\n *\n * This returns an object of the validation status and the cleaned Seed Phrase for safe low-level usage.\n * @param {String} strPhraseInput - The Seed Phrase string\n * @param {Boolean} fPopupConfirm - Allow a warning bypass popup if the Seed Phrase is unusual\n */\nexport async function cleanAndVerifySeedPhrase(\n strPhraseInput = '',\n fPopupConfirm = true\n) {\n // Clean the phrase (removing unnecessary spaces) and force to lowercase\n const strPhrase = strPhraseInput.trim().replace(/\\s+/g, ' ').toLowerCase();\n\n // Count the Words\n const nWordCount = strPhrase.trim().split(' ').length;\n\n // Ensure it's a word count that makes sense\n if (nWordCount === 12 || nWordCount === 24) {\n if (!validateMnemonic(strPhrase)) {\n // If a popup is allowed and Advanced Mode is enabled, warn the user that the\n // ... seed phrase is potentially bad, and ask for confirmation to proceed\n if (!fPopupConfirm || !fAdvancedMode)\n return {\n ok: false,\n msg: translation.importSeedErrorTypo,\n phrase: strPhrase,\n };\n\n // The reason we want to ask the user for confirmation is that the mnemonic\n // could have been generated with another app that has a different dictionary\n const fSkipWarning = await confirmPopup({\n title: translation.popupSeedPhraseBad,\n html: translation.popupSeedPhraseBadNote,\n });\n\n if (fSkipWarning) {\n // User is probably an Arch Linux user and used `-f`\n return {\n ok: true,\n msg: translation.importSeedErrorSkip,\n phrase: strPhrase,\n };\n } else {\n // User heeded the warning and rejected the phrase\n return {\n ok: false,\n msg: translation.importSeedError,\n phrase: strPhrase,\n };\n }\n } else {\n // Valid count and mnemonic\n return {\n ok: true,\n msg: translation.importSeedValid,\n phrase: strPhrase,\n };\n }\n } else {\n // Invalid count\n return {\n ok: false,\n msg: translation.importSeedErrorSize,\n phrase: strPhrase,\n };\n }\n}\n\n/**\n * Display a Seed Phrase popup to the user and optionally wait for a Seed Passphrase\n * @param {string} mnemonic - The Seed Phrase to display to the user\n * @returns {Promise} - The Mnemonic Passphrase (empty string if omitted by user)\n */\nfunction informUserOfMnemonic(mnemonic) {\n return new Promise((res, _) => {\n // Configure the modal\n $('#mnemonicModal').modal({ keyboard: false });\n\n // Render the Seed Phrase and configure the button\n doms.domMnemonicModalContent.innerText = mnemonic;\n doms.domMnemonicModalButton.onclick = () => {\n res(doms.domMnemonicModalPassphrase.value);\n $('#mnemonicModal').modal('hide');\n\n // Wipe the mnemonic displays of sensitive data\n doms.domMnemonicModalContent.innerText = '';\n doms.domMnemonicModalPassphrase.value = '';\n };\n\n // Display the modal\n $('#mnemonicModal').modal('show');\n });\n}\n\nexport async function encryptWallet(strPassword = '') {\n // Encrypt the wallet WIF with AES-GCM and a user-chosen password - suitable for browser storage\n let strEncWIF = await encrypt(masterKey.keyToBackup, strPassword);\n if (!strEncWIF) return false;\n\n // Hide the encryption warning\n doms.domGenKeyWarning.style.display = 'none';\n\n // Prepare to Add/Update an account in the DB\n const cAccount = new Account({\n publicKey: await masterKey.keyToExport,\n encWif: strEncWIF,\n });\n\n // Incase of a \"Change Password\", we check if an Account already exists\n const database = await Database.getInstance();\n if (await database.getAccount()) {\n // Update the existing Account (new encWif) in the DB\n await database.updateAccount(cAccount);\n } else {\n // Add the new Account to the DB\n await database.addAccount(cAccount);\n }\n\n // Remove the exit blocker, we can annoy the user less knowing the key is safe in their database!\n removeEventListener('beforeunload', beforeUnloadListener, {\n capture: true,\n });\n}\n\nexport async function decryptWallet(strPassword = '') {\n // Check if there's any encrypted WIF available\n const database = await Database.getInstance();\n const { encWif: strEncWIF } = await database.getAccount();\n if (!strEncWIF || strEncWIF.length < 1) return false;\n\n // Prompt to decrypt it via password\n const strDecWIF = await decrypt(strEncWIF, strPassword);\n if (!strDecWIF || strDecWIF === 'decryption failed!') {\n if (strDecWIF)\n return createAlert('warning', ALERTS.INCORRECT_PASSWORD, 6000);\n } else {\n await importWallet({\n newWif: strDecWIF,\n // Save the public key to disk for View Only mode\n fSavePublicKey: true,\n });\n return true;\n }\n}\n\n/**\n * @returns {Promise} If the wallet has an encrypted database backup\n */\nexport async function hasEncryptedWallet() {\n const database = await Database.getInstance();\n const account = await database.getAccount();\n return !!account?.encWif;\n}\n\n// If the privateKey is null then the user connected a hardware wallet\nexport function hasHardwareWallet() {\n if (!masterKey) return false;\n return masterKey.isHardwareWallet == true;\n}\n\nexport async function hasWalletUnlocked(fIncludeNetwork = false) {\n if (fIncludeNetwork && !getNetwork().enabled)\n return createAlert('warning', ALERTS.WALLET_OFFLINE_AUTOMATIC, 5500);\n if (!masterKey) {\n return createAlert(\n 'warning',\n tr(ALERTS.WALLET_UNLOCK_IMPORT, [\n {\n unlock: (await hasEncryptedWallet())\n ? 'unlock '\n : 'import/create',\n },\n ]),\n 3500\n );\n } else {\n return true;\n }\n}\n\nfunction createAddressConfirmation(address) {\n return `${translation.popupHardwareAddrCheck} ${strHardwareName}.\n
${address}
`;\n}\n\nexport async function getNewAddress({\n updateGUI = false,\n verify = false,\n} = {}) {\n const [address, path] = await masterKey.getNewAddress();\n if (verify && masterKey.isHardwareWallet) {\n // Generate address to present to the user without asking to verify\n const confAddress = await confirmPopup({\n title: ALERTS.CONFIRM_POPUP_VERIFY_ADDR,\n html: createAddressConfirmation(address),\n resolvePromise: masterKey.getAddress(path, { verify }),\n });\n if (address !== confAddress) {\n throw new Error('User did not verify address');\n }\n }\n\n // If we're generating a new address manually, then render the new address in our Receive Modal\n if (updateGUI) {\n guiRenderCurrentReceiveModal();\n }\n\n return [address, path];\n}\n\nexport let cHardwareWallet = null;\nexport let strHardwareName = '';\nlet transport;\nasync function getHardwareWalletKeys(\n path,\n xpub = false,\n verify = false,\n _attempts = 0\n) {\n try {\n // Check if we haven't setup a connection yet OR the previous connection disconnected\n if (!cHardwareWallet || transport._disconnectEmitted) {\n transport = await TransportWebUSB.create();\n cHardwareWallet = new AppBtc({ transport, currency: 'PIVX' });\n }\n\n // Update device info and fetch the pubkey\n strHardwareName =\n transport.device.manufacturerName +\n ' ' +\n transport.device.productName;\n\n // Prompt the user in both UIs\n if (verify) createAlert('info', ALERTS.WALLET_CONFIRM_L, 3500);\n const cPubKey = await cHardwareWallet.getWalletPublicKey(path, {\n verify,\n format: 'legacy',\n });\n\n if (xpub) {\n return createXpub({\n depth: 3,\n childNumber: 2147483648,\n chainCode: cPubKey.chainCode,\n publicKey: cPubKey.publicKey,\n });\n } else {\n return cPubKey.publicKey;\n }\n } catch (e) {\n if (e.message.includes('denied by the user')) {\n // User denied an operation\n return false;\n }\n\n // If there's no device, nudge the user to plug it in.\n if (e.message.toLowerCase().includes('no device selected')) {\n createAlert('info', ALERTS.WALLET_NO_HARDWARE, 10000);\n return false;\n }\n\n // If the device is unplugged, or connection lost through other means (such as spontanious device explosion)\n if (e.message.includes(\"Failed to execute 'transferIn'\")) {\n createAlert(\n 'info',\n tr(ALERTS.WALLET_HARDWARE_CONNECTION_LOST, [\n {\n hardwareWallet: strHardwareName,\n },\n ]),\n 10000\n );\n return false;\n }\n if (_attempts < 10) {\n // This is an ugly hack :(\n // in the event where multiple parts of the code decide to ask for an address, just\n // Retry at most 10 times waiting 200ms each time\n await sleep(200);\n return await getHardwareWalletKeys(\n path,\n xpub,\n verify,\n _attempts + 1\n );\n }\n\n // If the ledger is busy, just nudge the user.\n if (e.message.includes('is busy')) {\n createAlert(\n 'info',\n tr(ALERTS.WALLET_HARDWARE_BUSY, [\n {\n hardwareWallet: strHardwareName,\n },\n ]),\n 7500\n );\n return false;\n }\n\n // Check if this is an expected error\n if (!e.statusCode || !LEDGER_ERRS.has(e.statusCode)) {\n console.error(\n 'MISSING LEDGER ERROR-CODE TRANSLATION! - Please report this below error on our GitHub so we can handle it more nicely!'\n );\n console.error(e);\n }\n\n // Translate the error to a user-friendly string (if possible)\n createAlert(\n 'warning',\n tr(ALERTS.WALLET_HARDWARE_ERROR, [\n {\n hardwareWallet: strHardwareName,\n },\n {\n error: LEDGER_ERRS.get(e.statusCode),\n },\n ]),\n 5500\n );\n\n return false;\n }\n}\n","import { deriveAddress } from './wallet.js';\nimport { getSafeRand } from './misc.js';\n\nonmessage = function (_evt) {\n while (true) {\n const cKeypair = {};\n cKeypair.priv = getSafeRand();\n\n cKeypair.pub = deriveAddress({ pkBytes: cKeypair.priv });\n postMessage(cKeypair);\n }\n};\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n// the startup function\n__webpack_require__.x = () => {\n\t// Load entry module and return exports\n\t// This entry module depends on other loaded chunks and execution need to be delayed\n\tvar __webpack_exports__ = __webpack_require__.O(undefined, [621,369], () => (__webpack_require__(56691)))\n\t__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n\treturn __webpack_exports__;\n};\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"./\" + chunkId + \".mpw.js\";\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript)\n\t\tscriptUrl = document.currentScript.src\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) scriptUrl = scripts[scripts.length - 1].src\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","__webpack_require__.b = self.location + \"\";\n\n// object to store loaded chunks\n// \"1\" means \"already loaded\"\nvar installedChunks = {\n\t56: 1\n};\n\n// importScripts chunk loading\nvar installChunk = (data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\tfor(var moduleId in moreModules) {\n\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t}\n\t}\n\tif(runtime) runtime(__webpack_require__);\n\twhile(chunkIds.length)\n\t\tinstalledChunks[chunkIds.pop()] = 1;\n\tparentChunkLoadingFunction(data);\n};\n__webpack_require__.f.i = (chunkId, promises) => {\n\t// \"1\" is the signal for \"already loaded\"\n\tif(!installedChunks[chunkId]) {\n\t\tif(true) { // all chunks have JS\n\t\t\timportScripts(__webpack_require__.p + __webpack_require__.u(chunkId));\n\t\t}\n\t}\n};\n\nvar chunkLoadingGlobal = self[\"webpackChunkMPW\"] = self[\"webpackChunkMPW\"] || [];\nvar parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);\nchunkLoadingGlobal.push = installChunk;\n\n// no HMR\n\n// no HMR manifest","// run startup\nvar __webpack_exports__ = __webpack_require__.x();\n"],"names":["deferred","leafPrototypes","getProto","next","bytes","Buffer","toString","current","main","name","collateralInSats","isTestnet","TICKER","PUBKEY_PREFIX","STAKING_PREFIX","PUBKEY_ADDRESS","SECRET_KEY","BIP44_TYPE","BIP44_TYPE_LEDGER","PROTOCOL_VERSION","MASTERNODE_PORT","Explorers","url","Nodes","Consensus","UPGRADE_V6_0","undefined","budgetCycleBlocks","proposalFee","maxPaymentCycles","maxPayment","testnet","MarketSource","cData","strName","strEndpoint","async","this","Object","keys","length","fetch","json","e","console","warn","constructor","super","strCurrency","ensureCacheExists","market_data","current_price","val","Array","isArray","nDisplayDecimals","hit","time_to_sync","transaction","freeze","FALSE","PUSHDATA1","PUSHDATA2","PUSHDATA4","RESERVED","TRUE","NOP","VER","IF","NOTIF","VERIF","VERNOTIF","ELSE","ENDIF","VERIFY","RETURN","TOALTSTACK","FROMALTSTACK","IFDUP","DEPTH","DROP","DUP","NIP","OVER","PICK","ROLL","ROT","SWAP","TUCK","CAT","SUBSTR","LEFT","RIGHT","SIZE","INVERT","AND","OR","XOR","EQUAL","EQUALVERIFY","RESERVED1","RESERVED2","NEGATE","ABS","NOT","ADD","SUB","MUL","DIV","MOD","LSHIFT","RSHIFT","BOOLAND","BOOLOR","NUMEQUAL","NUMEQUALVERIFY","NUMNOTEQUAL","LESSTHAN","GREATERTHAN","LESSTHANOREQUAL","GREATERTHANOREQUAL","MIN","MAX","WITHIN","RIPEMD160","SHA1","SHA256","HASH160","HASH256","CODESEPARATOR","CHECKSIG","CHECKSIGVERIFY","CHECKMULTISIG","CHECKMULTISIGVERIFY","NOP1","NOP2","CHECKLOCKTIMEVERIFY","NOP3","NOP4","NOP5","NOP6","NOP7","NOP8","NOP9","NOP10","ZEROCOINMINT","ZEROCOINSPEND","ZEROCOINPUBLICSPEND","CHECKCOLDSTAKEVERIFY_LOF","CHECKCOLDSTAKEVERIFY","INVALIDOPCODE","static","db","close","masternode","_masterKey","store","objectStore","put","delete","promo","code","account","Account","error","createAlert","cDBAccount","strKey","isSameType","get","allowDeletion","getAccount","isEmpty","publicKey","cAccount","Masternode","getAll","map","PromoWallet","Settings","settings","oldSettings","getSettings","localStorage","analytics","explorer","node","translation","displayCurrency","setSettings","JSON","parse","addMasternode","ALERTS","MIGRATION_MASTERNODE_FAILURE","encwif","localProposals","encWif","addAccount","MIGRATION_ACCOUNT_FAILURE","confirmPopup","title","MIGRATION_ACCOUNT_FAILURE_TITLE","html","MIGRATION_ACCOUNT_FAILURE_HTML","sanitizeHTML","database","openDB","upgrade","oldVersion","log","createObjectStore","blocking","alert","window","location","reload","Map","cChainParams","instance","set","create","nSize","crypto","getRandomValues","Uint8Array","arr","pos","arrLen","strERR","Error","i","type","message","timeout","domAlert","document","createElement","typeIcon","classList","add","setTimeout","style","opacity","zIndex","innerHTML","destroy","clearTimeout","timer","remove","addEventListener","beautifyNumber","strNumber","strDecFontSize","includes","arrNumParts","split","strFontSize","eventEmitter","EventEmitter","id","path","sats","script","vin","vout","height","status","isDelegate","isReward","equalsUTXO","cUTXO","UTXOs","subscribeToNetwork","getUTXO","out","find","nBlocks","ms","Promise","res","_","removeUTXO","isAlreadyStored","some","getUTXOsByState","nState","filter","removeFromState","cNewUTXO","arrPendingUTXOs","addUTXO","newUTXO","updateUTXO","cStakeInput","txid","push","utxo","PENDING","CONFIRMED","autoRemoveUTXO","REMOVED","removeWithDelay","autoRemoveUTXOs","arrUTXOs","getConfirmed","getStandardUTXOs","getDelegatedUTXOs","getBalance","cMasternode","collateralTxId","outidx","reduce","a","b","cachedBlockCount","getDelegatedBalance","on","utxos","getUTXOFullInfo","TextEncoder","TextDecoder","updateTicker","domGuiBalanceValueCurrency","innerText","domGuiStakingValueCurrency","domSendAmountValueCurrency","domSendAmountCoinsTicker","domStakeAmountValueCurrency","domStakeAmountCoinsTicker","domUnstakeAmountValueCurrency","domUnstakeAmountCoinsTicker","updatePriceDisplay","domValue","fCold","nPrice","nCurrencyValue","nValue","cLocale","nAmount","Intl","supportedValuesOf","currency","currencyDisplay","maximumFractionDigits","minimumFractionDigits","optimiseCurrencyLocale","toLocaleString","updateGUI","nBalance","strBal","toFixed","nLen","domGuiBalance","domAvailToDelegate","domGuiBalanceValue","domGuiBalanceStaking","domAvailToUndelegate","domGuiStakingValue","errorHandler","text","element","reason","pkBytes","output","compress","pubKeyBytes","str","x","slice","compressPublicKey","pubKeyHashing","pubKeyHashRipemd160","ripemd160","pubKeyHashNetwork","buff","checksumPubKey","pubKeyPreBase","pubKeyHashNetworkLen","onmessage","_evt","cKeypair","priv","pub","postMessage","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","module","loaded","__webpack_modules__","call","m","__webpack_exports__","O","result","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","j","every","key","splice","r","n","getter","__esModule","d","getPrototypeOf","obj","t","value","mode","then","ns","def","indexOf","getOwnPropertyNames","forEach","definition","o","defineProperty","enumerable","f","chunkId","all","promises","u","miniCssF","g","globalThis","Function","prop","prototype","hasOwnProperty","Symbol","toStringTag","nmd","paths","children","scriptUrl","importScripts","currentScript","src","scripts","getElementsByTagName","replace","p","self","installedChunks","chunkLoadingGlobal","parentChunkLoadingFunction","bind","data","moreModules","runtime","pop"],"sourceRoot":""} \ No newline at end of file diff --git a/index.html b/index.html index 4c0a1db9d..421f2c66b 100644 --- a/index.html +++ b/index.html @@ -1 +1 @@ -My PIVX Wallet


My PIVX Wallet is
Loading

Create a
New Wallet

Create a new PIVX wallet, offering the most secure backup & security methods.


Create a new
Vanity Wallet

Create a wallet with a custom prefix, this can take a long time!

Note: addresses will always start with: D

Access your
Ledger Wallet

Use your Ledger Hardware wallet with MPW's familiar interface.


Go to
My Wallet

Import a PIVX wallet using a Private Key, xpriv, or Seed Phrase.



Staking
0 PIV
$- USD
Stake
Unstake
Reward History (-)
Unstake

MAX
PIV
USD
Stake

MAX
PIV
USD

Governance

From this tab you can check the proposals and, if you have a masternode, be a part of the DAO and vote!

Monthly Budget
- PIV
-
Budget Allocated
- PIV
-
Next Treasury Payout
Budget Allocated
- PIV
-
STATUSNAMEPAYMENTVOTESVOTE


Contested Proposals

These are proposals that received an overwhelming amount of downvotes, making it likely spam or a highly contestable proposal.


STATUSNAMEPAYMENTVOTESVOTE

Control your

Masternode

From this tab you can create and access one or more masternodes



Status

Last Seen


  • Wallet
  • Display
Wallet







Change Password

Display

Price data provided by CoinGecko


(-)


\ No newline at end of file +My PIVX Wallet


My PIVX Wallet is
Loading

Create a
New Wallet

Create a new PIVX wallet, offering the most secure backup & security methods.


Create a new
Vanity Wallet

Create a wallet with a custom prefix, this can take a long time!

Note: addresses will always start with: D

Access your
Ledger Wallet

Use your Ledger Hardware wallet with MPW's familiar interface.


Go to
My Wallet

Import a PIVX wallet using a Private Key, xpriv, or Seed Phrase.



Staking
0 PIV
$- USD
Stake
Unstake
Reward History (-)
Unstake

MAX
PIV
USD
Stake

MAX
PIV
USD

Governance

From this tab you can check the proposals and, if you have a masternode, be a part of the DAO and vote!

Monthly Budget
- PIV
-
Budget Allocated
- PIV
-
Next Treasury Payout
Budget Allocated
- PIV
-
STATUSNAMEPAYMENTVOTESVOTE


Contested Proposals

These are proposals that received an overwhelming amount of downvotes, making it likely spam or a highly contestable proposal.


STATUSNAMEPAYMENTVOTESVOTE

Control your

Masternode

From this tab you can create and access one or more masternodes



Status

Last Seen


  • Wallet
  • Display
Wallet







Change Password



This unlocks deeper functionality and customisation, but may be overwhelming and potentially dangerous for unexperienced users!

Display

Price data provided by CoinGecko


(-)


\ No newline at end of file diff --git a/mpw.js b/mpw.js index f57ac2c25..f6dc1825a 100644 --- a/mpw.js +++ b/mpw.js @@ -1,3 +1,3 @@ /*! For license information please see mpw.js.LICENSE.txt */ -var MPW;(()=>{var e,t,r,n,i={78244:(e,t,r)=>{var n={"./100-italic.css":2173,"./100.css":47846,"./200-italic.css":54412,"./200.css":12124,"./300-italic.css":54893,"./300.css":58427,"./400-italic.css":10207,"./400.css":39684,"./500-italic.css":82425,"./500.css":41536,"./600-italic.css":65783,"./600.css":99467,"./700-italic.css":88878,"./700.css":66473,"./800-italic.css":3432,"./800.css":85715,"./900-italic.css":64931,"./900.css":53694,"./cyrillic-100-italic.css":72704,"./cyrillic-100.css":25996,"./cyrillic-200-italic.css":22770,"./cyrillic-200.css":39523,"./cyrillic-300-italic.css":84313,"./cyrillic-300.css":26598,"./cyrillic-400-italic.css":2802,"./cyrillic-400.css":86258,"./cyrillic-500-italic.css":14115,"./cyrillic-500.css":91095,"./cyrillic-600-italic.css":18291,"./cyrillic-600.css":787,"./cyrillic-700-italic.css":79193,"./cyrillic-700.css":38011,"./cyrillic-800-italic.css":98236,"./cyrillic-800.css":44225,"./cyrillic-900-italic.css":39717,"./cyrillic-900.css":24014,"./cyrillic-ext-100-italic.css":58471,"./cyrillic-ext-100.css":64831,"./cyrillic-ext-200-italic.css":28776,"./cyrillic-ext-200.css":30513,"./cyrillic-ext-300-italic.css":21120,"./cyrillic-ext-300.css":90840,"./cyrillic-ext-400-italic.css":32514,"./cyrillic-ext-400.css":89517,"./cyrillic-ext-500-italic.css":18006,"./cyrillic-ext-500.css":43907,"./cyrillic-ext-600-italic.css":38684,"./cyrillic-ext-600.css":4300,"./cyrillic-ext-700-italic.css":24052,"./cyrillic-ext-700.css":80205,"./cyrillic-ext-800-italic.css":64446,"./cyrillic-ext-800.css":14118,"./cyrillic-ext-900-italic.css":39979,"./cyrillic-ext-900.css":23943,"./cyrillic-ext.css":58985,"./cyrillic.css":54113,"./index.css":22784,"./latin-100-italic.css":80316,"./latin-100.css":29450,"./latin-200-italic.css":21412,"./latin-200.css":92982,"./latin-300-italic.css":40162,"./latin-300.css":57006,"./latin-400-italic.css":69649,"./latin-400.css":95686,"./latin-500-italic.css":21509,"./latin-500.css":66622,"./latin-600-italic.css":90001,"./latin-600.css":36225,"./latin-700-italic.css":49026,"./latin-700.css":6210,"./latin-800-italic.css":52728,"./latin-800.css":17182,"./latin-900-italic.css":46164,"./latin-900.css":2837,"./latin-ext-100-italic.css":51516,"./latin-ext-100.css":14318,"./latin-ext-200-italic.css":42936,"./latin-ext-200.css":84112,"./latin-ext-300-italic.css":11971,"./latin-ext-300.css":61492,"./latin-ext-400-italic.css":66147,"./latin-ext-400.css":28571,"./latin-ext-500-italic.css":15429,"./latin-ext-500.css":87253,"./latin-ext-600-italic.css":9190,"./latin-ext-600.css":91568,"./latin-ext-700-italic.css":29183,"./latin-ext-700.css":98827,"./latin-ext-800-italic.css":5279,"./latin-ext-800.css":73757,"./latin-ext-900-italic.css":20317,"./latin-ext-900.css":61451,"./latin-ext.css":21213,"./latin.css":55415,"./variable-italic.css":53818,"./variable.css":47385,"./vietnamese-100-italic.css":50482,"./vietnamese-100.css":22069,"./vietnamese-200-italic.css":15460,"./vietnamese-200.css":15344,"./vietnamese-300-italic.css":17074,"./vietnamese-300.css":92997,"./vietnamese-400-italic.css":96611,"./vietnamese-400.css":51247,"./vietnamese-500-italic.css":78467,"./vietnamese-500.css":7726,"./vietnamese-600-italic.css":74304,"./vietnamese-600.css":91688,"./vietnamese-700-italic.css":38645,"./vietnamese-700.css":25482,"./vietnamese-800-italic.css":28594,"./vietnamese-800.css":7048,"./vietnamese-900-italic.css":25701,"./vietnamese-900.css":67074,"./vietnamese.css":35211};function i(e){var t=o(e);return r(t)}function o(e){if(!r.o(n,e)){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}return n[e]}i.keys=function(){return Object.keys(n)},i.resolve=o,e.exports=i,i.id=78244},14371:(e,t,r)=>{"use strict";var n=r(89509).Buffer;e.exports=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r>>0,l=new Uint8Array(a);e[r];){var d=t[e.charCodeAt(r)];if(255===d)return;for(var f=0,h=a-1;(0!==d||f>>0,l[h]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");o=f,r++}for(var p=a-o;p!==a&&0===l[p];)p++;var g=n.allocUnsafe(i+(a-p));g.fill(0,0,i);for(var m=i;p!==a;)g[m++]=l[p++];return g}return{encode:function(t){if((Array.isArray(t)||t instanceof Uint8Array)&&(t=n.from(t)),!n.isBuffer(t))throw new TypeError("Expected Buffer");if(0===t.length)return"";for(var r=0,i=0,o=0,a=t.length;o!==a&&0===t[o];)o++,r++;for(var u=(a-o)*l+1>>>0,d=new Uint8Array(u);o!==a;){for(var f=t[o],h=0,p=u-1;(0!==f||h>>0,d[p]=f%s>>>0,f=f/s>>>0;if(0!==f)throw new Error("Non-zero carry");i=h,o++}for(var g=u-i;g!==u&&0===d[g];)g++;for(var m=c.repeat(r);g{var n=r(14371);e.exports=n("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},39809:(e,t,r)=>{"use strict";const n=t;n.bignum=r(13550),n.define=r(22500).define,n.base=r(71979),n.constants=r(36826),n.decoders=r(78307),n.encoders=r(56579)},22500:(e,t,r)=>{"use strict";const n=r(56579),i=r(78307),o=r(35717);function a(e,t){this.name=e,this.body=t,this.decoders={},this.encoders={}}t.define=function(e,t){return new a(e,t)},a.prototype._createNamed=function(e){const t=this.name;function r(e){this._initNamed(e,t)}return o(r,e),r.prototype._initNamed=function(t,r){e.call(this,t,r)},new r(this)},a.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(i[e])),this.decoders[e]},a.prototype.decode=function(e,t,r){return this._getDecoder(t).decode(e,r)},a.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(n[e])),this.encoders[e]},a.prototype.encode=function(e,t,r){return this._getEncoder(t).encode(e,r)}},36625:(e,t,r)=>{"use strict";const n=r(35717),i=r(98465).b,o=r(2399).Buffer;function a(e,t){i.call(this,t),o.isBuffer(e)?(this.base=e,this.offset=0,this.length=e.length):this.error("Input not Buffer")}function s(e,t){if(Array.isArray(e))this.length=0,this.value=e.map((function(e){return s.isEncoderBuffer(e)||(e=new s(e,t)),this.length+=e.length,e}),this);else if("number"==typeof e){if(!(0<=e&&e<=255))return t.error("non-byte EncoderBuffer value");this.value=e,this.length=1}else if("string"==typeof e)this.value=e,this.length=o.byteLength(e);else{if(!o.isBuffer(e))return t.error("Unsupported type: "+typeof e);this.value=e,this.length=e.length}}n(a,i),t.C=a,a.isDecoderBuffer=function(e){return e instanceof a||"object"==typeof e&&o.isBuffer(e.base)&&"DecoderBuffer"===e.constructor.name&&"number"==typeof e.offset&&"number"==typeof e.length&&"function"==typeof e.save&&"function"==typeof e.restore&&"function"==typeof e.isEmpty&&"function"==typeof e.readUInt8&&"function"==typeof e.skip&&"function"==typeof e.raw},a.prototype.save=function(){return{offset:this.offset,reporter:i.prototype.save.call(this)}},a.prototype.restore=function(e){const t=new a(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,i.prototype.restore.call(this,e.reporter),t},a.prototype.isEmpty=function(){return this.offset===this.length},a.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")},a.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");const r=new a(this.base);return r._reporterState=this._reporterState,r.offset=this.offset,r.length=this.offset+e,this.offset+=e,r},a.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)},t.R=s,s.isEncoderBuffer=function(e){return e instanceof s||"object"==typeof e&&"EncoderBuffer"===e.constructor.name&&"number"==typeof e.length&&"function"==typeof e.join},s.prototype.join=function(e,t){return e||(e=o.alloc(this.length)),t||(t=0),0===this.length||(Array.isArray(this.value)?this.value.forEach((function(r){r.join(e,t),t+=r.length})):("number"==typeof this.value?e[t]=this.value:"string"==typeof this.value?e.write(this.value,t):o.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length)),e}},71979:(e,t,r)=>{"use strict";const n=t;n.Reporter=r(98465).b,n.DecoderBuffer=r(36625).C,n.EncoderBuffer=r(36625).R,n.Node=r(41949)},41949:(e,t,r)=>{"use strict";const n=r(98465).b,i=r(36625).R,o=r(36625).C,a=r(79746),s=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],c=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(s);function u(e,t,r){const n={};this._baseState=n,n.name=r,n.enc=e,n.parent=t||null,n.children=null,n.tag=null,n.args=null,n.reverseArgs=null,n.choice=null,n.optional=!1,n.any=!1,n.obj=!1,n.use=null,n.useDecoder=null,n.key=null,n.default=null,n.explicit=null,n.implicit=null,n.contains=null,n.parent||(n.children=[],this._wrap())}e.exports=u;const l=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];u.prototype.clone=function(){const e=this._baseState,t={};l.forEach((function(r){t[r]=e[r]}));const r=new this.constructor(t.parent);return r._baseState=t,r},u.prototype._wrap=function(){const e=this._baseState;c.forEach((function(t){this[t]=function(){const r=new this.constructor(this);return e.children.push(r),r[t].apply(r,arguments)}}),this)},u.prototype._init=function(e){const t=this._baseState;a(null===t.parent),e.call(this),t.children=t.children.filter((function(e){return e._baseState.parent===this}),this),a.equal(t.children.length,1,"Root node can have only one child")},u.prototype._useArgs=function(e){const t=this._baseState,r=e.filter((function(e){return e instanceof this.constructor}),this);e=e.filter((function(e){return!(e instanceof this.constructor)}),this),0!==r.length&&(a(null===t.children),t.children=r,r.forEach((function(e){e._baseState.parent=this}),this)),0!==e.length&&(a(null===t.args),t.args=e,t.reverseArgs=e.map((function(e){if("object"!=typeof e||e.constructor!==Object)return e;const t={};return Object.keys(e).forEach((function(r){r==(0|r)&&(r|=0);const n=e[r];t[n]=r})),t})))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach((function(e){u.prototype[e]=function(){const t=this._baseState;throw new Error(e+" not implemented for encoding: "+t.enc)}})),s.forEach((function(e){u.prototype[e]=function(){const t=this._baseState,r=Array.prototype.slice.call(arguments);return a(null===t.tag),t.tag=e,this._useArgs(r),this}})),u.prototype.use=function(e){a(e);const t=this._baseState;return a(null===t.use),t.use=e,this},u.prototype.optional=function(){return this._baseState.optional=!0,this},u.prototype.def=function(e){const t=this._baseState;return a(null===t.default),t.default=e,t.optional=!0,this},u.prototype.explicit=function(e){const t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.explicit=e,this},u.prototype.implicit=function(e){const t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.implicit=e,this},u.prototype.obj=function(){const e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,0!==t.length&&this._useArgs(t),this},u.prototype.key=function(e){const t=this._baseState;return a(null===t.key),t.key=e,this},u.prototype.any=function(){return this._baseState.any=!0,this},u.prototype.choice=function(e){const t=this._baseState;return a(null===t.choice),t.choice=e,this._useArgs(Object.keys(e).map((function(t){return e[t]}))),this},u.prototype.contains=function(e){const t=this._baseState;return a(null===t.use),t.contains=e,this},u.prototype._decode=function(e,t){const r=this._baseState;if(null===r.parent)return e.wrapResult(r.children[0]._decode(e,t));let n,i=r.default,a=!0,s=null;if(null!==r.key&&(s=e.enterKey(r.key)),r.optional){let n=null;if(null!==r.explicit?n=r.explicit:null!==r.implicit?n=r.implicit:null!==r.tag&&(n=r.tag),null!==n||r.any){if(a=this._peekTag(e,n,r.any),e.isError(a))return a}else{const n=e.save();try{null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t),a=!0}catch(e){a=!1}e.restore(n)}}if(r.obj&&a&&(n=e.enterObject()),a){if(null!==r.explicit){const t=this._decodeTag(e,r.explicit);if(e.isError(t))return t;e=t}const n=e.offset;if(null===r.use&&null===r.choice){let t;r.any&&(t=e.save());const n=this._decodeTag(e,null!==r.implicit?r.implicit:r.tag,r.any);if(e.isError(n))return n;r.any?i=e.raw(t):e=n}if(t&&t.track&&null!==r.tag&&t.track(e.path(),n,e.length,"tagged"),t&&t.track&&null!==r.tag&&t.track(e.path(),e.offset,e.length,"content"),r.any||(i=null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t)),e.isError(i))return i;if(r.any||null!==r.choice||null===r.children||r.children.forEach((function(r){r._decode(e,t)})),r.contains&&("octstr"===r.tag||"bitstr"===r.tag)){const n=new o(i);i=this._getUse(r.contains,e._reporterState.obj)._decode(n,t)}}return r.obj&&a&&(i=e.leaveObject(n)),null===r.key||null===i&&!0!==a?null!==s&&e.exitKey(s):e.leaveKey(s,r.key,i),i},u.prototype._decodeGeneric=function(e,t,r){const n=this._baseState;return"seq"===e||"set"===e?null:"seqof"===e||"setof"===e?this._decodeList(t,e,n.args[0],r):/str$/.test(e)?this._decodeStr(t,e,r):"objid"===e&&n.args?this._decodeObjid(t,n.args[0],n.args[1],r):"objid"===e?this._decodeObjid(t,null,null,r):"gentime"===e||"utctime"===e?this._decodeTime(t,e,r):"null_"===e?this._decodeNull(t,r):"bool"===e?this._decodeBool(t,r):"objDesc"===e?this._decodeStr(t,e,r):"int"===e||"enum"===e?this._decodeInt(t,n.args&&n.args[0],r):null!==n.use?this._getUse(n.use,t._reporterState.obj)._decode(t,r):t.error("unknown tag: "+e)},u.prototype._getUse=function(e,t){const r=this._baseState;return r.useDecoder=this._use(e,t),a(null===r.useDecoder._baseState.parent),r.useDecoder=r.useDecoder._baseState.children[0],r.implicit!==r.useDecoder._baseState.implicit&&(r.useDecoder=r.useDecoder.clone(),r.useDecoder._baseState.implicit=r.implicit),r.useDecoder},u.prototype._decodeChoice=function(e,t){const r=this._baseState;let n=null,i=!1;return Object.keys(r.choice).some((function(o){const a=e.save(),s=r.choice[o];try{const r=s._decode(e,t);if(e.isError(r))return!1;n={type:o,value:r},i=!0}catch(t){return e.restore(a),!1}return!0}),this),i?n:e.error("Choice not matched")},u.prototype._createEncoderBuffer=function(e){return new i(e,this.reporter)},u.prototype._encode=function(e,t,r){const n=this._baseState;if(null!==n.default&&n.default===e)return;const i=this._encodeValue(e,t,r);return void 0===i||this._skipDefault(i,t,r)?void 0:i},u.prototype._encodeValue=function(e,t,r){const i=this._baseState;if(null===i.parent)return i.children[0]._encode(e,t||new n);let o=null;if(this.reporter=t,i.optional&&void 0===e){if(null===i.default)return;e=i.default}let a=null,s=!1;if(i.any)o=this._createEncoderBuffer(e);else if(i.choice)o=this._encodeChoice(e,t);else if(i.contains)a=this._getUse(i.contains,r)._encode(e,t),s=!0;else if(i.children)a=i.children.map((function(r){if("null_"===r._baseState.tag)return r._encode(null,t,e);if(null===r._baseState.key)return t.error("Child should have a key");const n=t.enterKey(r._baseState.key);if("object"!=typeof e)return t.error("Child expected, but input is not object");const i=r._encode(e[r._baseState.key],t,e);return t.leaveKey(n),i}),this).filter((function(e){return e})),a=this._createEncoderBuffer(a);else if("seqof"===i.tag||"setof"===i.tag){if(!i.args||1!==i.args.length)return t.error("Too many args for : "+i.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");const r=this.clone();r._baseState.implicit=null,a=this._createEncoderBuffer(e.map((function(r){const n=this._baseState;return this._getUse(n.args[0],e)._encode(r,t)}),r))}else null!==i.use?o=this._getUse(i.use,r)._encode(e,t):(a=this._encodePrimitive(i.tag,e),s=!0);if(!i.any&&null===i.choice){const e=null!==i.implicit?i.implicit:i.tag,r=null===i.implicit?"universal":"context";null===e?null===i.use&&t.error("Tag could be omitted only for .use()"):null===i.use&&(o=this._encodeComposite(e,s,r,a))}return null!==i.explicit&&(o=this._encodeComposite(i.explicit,!1,"context",o)),o},u.prototype._encodeChoice=function(e,t){const r=this._baseState,n=r.choice[e.type];return n||a(!1,e.type+" not found in "+JSON.stringify(Object.keys(r.choice))),n._encode(e.value,t)},u.prototype._encodePrimitive=function(e,t){const r=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if("objid"===e&&r.args)return this._encodeObjid(t,r.reverseArgs[0],r.args[1]);if("objid"===e)return this._encodeObjid(t,null,null);if("gentime"===e||"utctime"===e)return this._encodeTime(t,e);if("null_"===e)return this._encodeNull();if("int"===e||"enum"===e)return this._encodeInt(t,r.args&&r.reverseArgs[0]);if("bool"===e)return this._encodeBool(t);if("objDesc"===e)return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)},u.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)},u.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(e)}},98465:(e,t,r)=>{"use strict";const n=r(35717);function i(e){this._reporterState={obj:null,path:[],options:e||{},errors:[]}}function o(e,t){this.path=e,this.rethrow(t)}t.b=i,i.prototype.isError=function(e){return e instanceof o},i.prototype.save=function(){const e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}},i.prototype.restore=function(e){const t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)},i.prototype.enterKey=function(e){return this._reporterState.path.push(e)},i.prototype.exitKey=function(e){const t=this._reporterState;t.path=t.path.slice(0,e-1)},i.prototype.leaveKey=function(e,t,r){const n=this._reporterState;this.exitKey(e),null!==n.obj&&(n.obj[t]=r)},i.prototype.path=function(){return this._reporterState.path.join("/")},i.prototype.enterObject=function(){const e=this._reporterState,t=e.obj;return e.obj={},t},i.prototype.leaveObject=function(e){const t=this._reporterState,r=t.obj;return t.obj=e,r},i.prototype.error=function(e){let t;const r=this._reporterState,n=e instanceof o;if(t=n?e:new o(r.path.map((function(e){return"["+JSON.stringify(e)+"]"})).join(""),e.message||e,e.stack),!r.options.partial)throw t;return n||r.errors.push(t),t},i.prototype.wrapResult=function(e){const t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e},n(o,Error),o.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,o),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},70160:(e,t)=>{"use strict";function r(e){const t={};return Object.keys(e).forEach((function(r){(0|r)==r&&(r|=0);const n=e[r];t[n]=r})),t}t.tagClass={0:"universal",1:"application",2:"context",3:"private"},t.tagClassByName=r(t.tagClass),t.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},t.tagByName=r(t.tag)},36826:(e,t,r)=>{"use strict";const n=t;n._reverse=function(e){const t={};return Object.keys(e).forEach((function(r){(0|r)==r&&(r|=0);const n=e[r];t[n]=r})),t},n.der=r(70160)},41671:(e,t,r)=>{"use strict";const n=r(35717),i=r(13550),o=r(36625).C,a=r(41949),s=r(70160);function c(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new u,this.tree._init(e.body)}function u(e){a.call(this,"der",e)}function l(e,t){let r=e.readUInt8(t);if(e.isError(r))return r;const n=s.tagClass[r>>6],i=0==(32&r);if(31==(31&r)){let n=r;for(r=0;128==(128&n);){if(n=e.readUInt8(t),e.isError(n))return n;r<<=7,r|=127&n}}else r&=31;return{cls:n,primitive:i,tag:r,tagStr:s.tag[r]}}function d(e,t,r){let n=e.readUInt8(r);if(e.isError(n))return n;if(!t&&128===n)return null;if(0==(128&n))return n;const i=127&n;if(i>4)return e.error("length octect is too long");n=0;for(let t=0;t{"use strict";const n=t;n.der=r(41671),n.pem=r(59631)},59631:(e,t,r)=>{"use strict";const n=r(35717),i=r(2399).Buffer,o=r(41671);function a(e){o.call(this,e),this.enc="pem"}n(a,o),e.exports=a,a.prototype.decode=function(e,t){const r=e.toString().split(/[\r\n]+/g),n=t.label.toUpperCase(),a=/^-----(BEGIN|END) ([^-]+)-----$/;let s=-1,c=-1;for(let e=0;e{"use strict";const n=r(35717),i=r(2399).Buffer,o=r(41949),a=r(70160);function s(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new c,this.tree._init(e.body)}function c(e){o.call(this,"der",e)}function u(e){return e<10?"0"+e:e}e.exports=s,s.prototype.encode=function(e,t){return this.tree._encode(e,t).join()},n(c,o),c.prototype._encodeComposite=function(e,t,r,n){const o=function(e,t,r,n){let i;if("seqof"===e?e="seq":"setof"===e&&(e="set"),a.tagByName.hasOwnProperty(e))i=a.tagByName[e];else{if("number"!=typeof e||(0|e)!==e)return n.error("Unknown tag: "+e);i=e}return i>=31?n.error("Multi-octet tag encoding unsupported"):(t||(i|=32),i|=a.tagClassByName[r||"universal"]<<6,i)}(e,t,r,this.reporter);if(n.length<128){const e=i.alloc(2);return e[0]=o,e[1]=n.length,this._createEncoderBuffer([e,n])}let s=1;for(let e=n.length;e>=256;e>>=8)s++;const c=i.alloc(2+s);c[0]=o,c[1]=128|s;for(let e=1+s,t=n.length;t>0;e--,t>>=8)c[e]=255&t;return this._createEncoderBuffer([c,n])},c.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){const t=i.alloc(2*e.length);for(let r=0;r=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}let n=0;for(let t=0;t=128;r>>=7)n++}const o=i.alloc(n);let a=o.length-1;for(let t=e.length-1;t>=0;t--){let r=e[t];for(o[a--]=127&r;(r>>=7)>0;)o[a--]=128|127&r}return this._createEncoderBuffer(o)},c.prototype._encodeTime=function(e,t){let r;const n=new Date(e);return"gentime"===t?r=[u(n.getUTCFullYear()),u(n.getUTCMonth()+1),u(n.getUTCDate()),u(n.getUTCHours()),u(n.getUTCMinutes()),u(n.getUTCSeconds()),"Z"].join(""):"utctime"===t?r=[u(n.getUTCFullYear()%100),u(n.getUTCMonth()+1),u(n.getUTCDate()),u(n.getUTCHours()),u(n.getUTCMinutes()),u(n.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(r,"octstr")},c.prototype._encodeNull=function(){return this._createEncoderBuffer("")},c.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!i.isBuffer(e)){const t=e.toArray();!e.sign&&128&t[0]&&t.unshift(0),e=i.from(t)}if(i.isBuffer(e)){let t=e.length;0===e.length&&t++;const r=i.alloc(t);return e.copy(r),0===e.length&&(r[0]=0),this._createEncoderBuffer(r)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);let r=1;for(let t=e;t>=256;t>>=8)r++;const n=new Array(r);for(let t=n.length-1;t>=0;t--)n[t]=255&e,e>>=8;return 128&n[0]&&n.unshift(0),this._createEncoderBuffer(i.from(n))},c.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)},c.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},c.prototype._skipDefault=function(e,t,r){const n=this._baseState;let i;if(null===n.default)return!1;const o=e.join();if(void 0===n.defaultBuffer&&(n.defaultBuffer=this._encodeValue(n.default,t,r).join()),o.length!==n.defaultBuffer.length)return!1;for(i=0;i{"use strict";const n=t;n.der=r(66984),n.pem=r(2883)},2883:(e,t,r)=>{"use strict";const n=r(35717),i=r(66984);function o(e){i.call(this,e),this.enc="pem"}n(o,i),e.exports=o,o.prototype.encode=function(e,t){const r=i.prototype.encode.call(this,e).toString("base64"),n=["-----BEGIN "+t.label+"-----"];for(let e=0;e{"use strict";var n=r(34155),i=r(25108);function o(e){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o(e)}var a,s,c=r(62136).codes,u=c.ERR_AMBIGUOUS_ARGUMENT,l=c.ERR_INVALID_ARG_TYPE,d=c.ERR_INVALID_ARG_VALUE,f=c.ERR_INVALID_RETURN_VALUE,h=c.ERR_MISSING_ARGS,p=r(25961),g=r(89539).inspect,m=r(89539).types,y=m.isPromise,b=m.isRegExp,v=Object.assign?Object.assign:r(8091).assign,w=Object.is?Object.is:r(20609);function _(){var e=r(19158);a=e.isDeepEqual,s=e.isDeepStrictEqual}new Map;var E=!1,S=e.exports=x,T={};function A(e){if(e.message instanceof Error)throw e.message;throw new p(e)}function I(e,t,r,n){if(!r){var i=!1;if(0===t)i=!0,n="No value argument passed to `assert.ok()`";else if(n instanceof Error)throw n;var o=new p({actual:r,expected:!0,message:n,operator:"==",stackStartFn:e});throw o.generatedMessage=i,o}}function x(){for(var e=arguments.length,t=new Array(e),r=0;r1?r-1:0),i=1;i1?r-1:0),i=1;i1?r-1:0),i=1;i1?r-1:0),i=1;i{"use strict";var n=r(34155);function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){for(var r=0;re.length)&&(r=e.length),e.substring(r-t.length,r)===t}var y="",b="",v="",w="",_={deepStrictEqual:"Expected values to be strictly deep-equal:",strictEqual:"Expected values to be strictly equal:",strictEqualObject:'Expected "actual" to be reference-equal to "expected":',deepEqual:"Expected values to be loosely deep-equal:",equal:"Expected values to be loosely equal:",notDeepStrictEqual:'Expected "actual" not to be strictly deep-equal to:',notStrictEqual:'Expected "actual" to be strictly unequal to:',notStrictEqualObject:'Expected "actual" not to be reference-equal to "expected":',notDeepEqual:'Expected "actual" not to be loosely deep-equal to:',notEqual:'Expected "actual" to be loosely unequal to:',notIdentical:"Values identical but not reference-equal:"};function E(e){var t=Object.keys(e),r=Object.create(Object.getPrototypeOf(e));return t.forEach((function(t){r[t]=e[t]})),Object.defineProperty(r,"message",{value:e.message}),r}function S(e){return p(e,{compact:!1,customInspect:!1,depth:1e3,maxArrayLength:1/0,showHidden:!1,breakLength:1/0,showProxy:!1,sorted:!0,getters:!0})}var T=function(e){function t(e){var r;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),"object"!==h(e)||null===e)throw new g("options","Object",e);var i=e.message,o=e.operator,c=e.stackStartFn,u=e.actual,l=e.expected,d=Error.stackTraceLimit;if(Error.stackTraceLimit=0,null!=i)r=a(this,f(t).call(this,String(i)));else if(n.stderr&&n.stderr.isTTY&&(n.stderr&&n.stderr.getColorDepth&&1!==n.stderr.getColorDepth()?(y="",b="",w="",v=""):(y="",b="",w="",v="")),"object"===h(u)&&null!==u&&"object"===h(l)&&null!==l&&"stack"in u&&u instanceof Error&&"stack"in l&&l instanceof Error&&(u=E(u),l=E(l)),"deepStrictEqual"===o||"strictEqual"===o)r=a(this,f(t).call(this,function(e,t,r){var i="",o="",a=0,s="",c=!1,u=S(e),l=u.split("\n"),d=S(t).split("\n"),f=0,p="";if("strictEqual"===r&&"object"===h(e)&&"object"===h(t)&&null!==e&&null!==t&&(r="strictEqualObject"),1===l.length&&1===d.length&&l[0]!==d[0]){var g=l[0].length+d[0].length;if(g<=10){if(!("object"===h(e)&&null!==e||"object"===h(t)&&null!==t||0===e&&0===t))return"".concat(_[r],"\n\n")+"".concat(l[0]," !== ").concat(d[0],"\n")}else if("strictEqualObject"!==r&&g<(n.stderr&&n.stderr.isTTY?n.stderr.columns:80)){for(;l[0][f]===d[0][f];)f++;f>2&&(p="\n ".concat(function(e,t){if(t=Math.floor(t),0==e.length||0==t)return"";var r=e.length*t;for(t=Math.floor(Math.log(t)/Math.log(2));t;)e+=e,t--;return e+e.substring(0,r-e.length)}(" ",f),"^"),f=0)}}for(var E=l[l.length-1],T=d[d.length-1];E===T&&(f++<2?s="\n ".concat(E).concat(s):i=E,l.pop(),d.pop(),0!==l.length&&0!==d.length);)E=l[l.length-1],T=d[d.length-1];var A=Math.max(l.length,d.length);if(0===A){var I=u.split("\n");if(I.length>30)for(I[26]="".concat(y,"...").concat(w);I.length>27;)I.pop();return"".concat(_.notIdentical,"\n\n").concat(I.join("\n"),"\n")}f>3&&(s="\n".concat(y,"...").concat(w).concat(s),c=!0),""!==i&&(s="\n ".concat(i).concat(s),i="");var x=0,O=_[r]+"\n".concat(b,"+ actual").concat(w," ").concat(v,"- expected").concat(w),k=" ".concat(y,"...").concat(w," Lines skipped");for(f=0;f1&&f>2&&(P>4?(o+="\n".concat(y,"...").concat(w),c=!0):P>3&&(o+="\n ".concat(d[f-2]),x++),o+="\n ".concat(d[f-1]),x++),a=f,i+="\n".concat(v,"-").concat(w," ").concat(d[f]),x++;else if(d.length1&&f>2&&(P>4?(o+="\n".concat(y,"...").concat(w),c=!0):P>3&&(o+="\n ".concat(l[f-2]),x++),o+="\n ".concat(l[f-1]),x++),a=f,o+="\n".concat(b,"+").concat(w," ").concat(l[f]),x++;else{var C=d[f],N=l[f],M=N!==C&&(!m(N,",")||N.slice(0,-1)!==C);M&&m(C,",")&&C.slice(0,-1)===N&&(M=!1,N+=","),M?(P>1&&f>2&&(P>4?(o+="\n".concat(y,"...").concat(w),c=!0):P>3&&(o+="\n ".concat(l[f-2]),x++),o+="\n ".concat(l[f-1]),x++),a=f,o+="\n".concat(b,"+").concat(w," ").concat(N),i+="\n".concat(v,"-").concat(w," ").concat(C),x+=2):(o+=i,i="",1!==P&&0!==f||(o+="\n ".concat(N),x++))}if(x>20&&f30)for(T[26]="".concat(y,"...").concat(w);T.length>27;)T.pop();r=1===T.length?a(this,f(t).call(this,"".concat(p," ").concat(T[0]))):a(this,f(t).call(this,"".concat(p,"\n\n").concat(T.join("\n"),"\n")))}else{var A=S(u),I="",x=_[o];"notDeepEqual"===o||"notEqual"===o?(A="".concat(_[o],"\n\n").concat(A)).length>1024&&(A="".concat(A.slice(0,1021),"...")):(I="".concat(S(l)),A.length>512&&(A="".concat(A.slice(0,509),"...")),I.length>512&&(I="".concat(I.slice(0,509),"...")),"deepEqual"===o||"equal"===o?A="".concat(x,"\n\n").concat(A,"\n\nshould equal\n\n"):I=" ".concat(o," ").concat(I)),r=a(this,f(t).call(this,"".concat(A).concat(I)))}return Error.stackTraceLimit=d,r.generatedMessage=!i,Object.defineProperty(s(r),"name",{value:"AssertionError [ERR_ASSERTION]",enumerable:!1,writable:!0,configurable:!0}),r.code="ERR_ASSERTION",r.actual=u,r.expected=l,r.operator=o,Error.captureStackTrace&&Error.captureStackTrace(s(r),c),r.stack,r.name="AssertionError",a(r)}var r,c;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&d(e,t)}(t,e),r=t,c=[{key:"toString",value:function(){return"".concat(this.name," [").concat(this.code,"]: ").concat(this.message)}},{key:p.custom,value:function(e,t){return p(this,function(e){for(var t=1;t{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function i(e){return i=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},i(e)}function o(e,t){return o=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},o(e,t)}var a,s,c={};function u(e,t,r){r||(r=Error);var a=function(r){function a(r,o,s){var c;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,a),c=function(e,t){return!t||"object"!==n(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}(this,i(a).call(this,function(e,r,n){return"string"==typeof t?t:t(e,r,n)}(r,o,s))),c.code=e,c}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&o(e,t)}(a,r),a}(r);c[e]=a}function l(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map((function(e){return String(e)})),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:2===r?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}u("ERR_AMBIGUOUS_ARGUMENT",'The "%s" argument is ambiguous. %s',TypeError),u("ERR_INVALID_ARG_TYPE",(function(e,t,i){var o,s,c,u,d;if(void 0===a&&(a=r(69282)),a("string"==typeof e,"'name' must be a string"),"string"==typeof t&&(s="not ",t.substr(0,s.length)===s)?(o="must not be",t=t.replace(/^not /,"")):o="must be",function(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}(e," argument"))c="The ".concat(e," ").concat(o," ").concat(l(t,"type"));else{var f=("number"!=typeof d&&(d=0),d+".".length>(u=e).length||-1===u.indexOf(".",d)?"argument":"property");c='The "'.concat(e,'" ').concat(f," ").concat(o," ").concat(l(t,"type"))}return c+". Received type ".concat(n(i))}),TypeError),u("ERR_INVALID_ARG_VALUE",(function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"is invalid";void 0===s&&(s=r(89539));var i=s.inspect(t);return i.length>128&&(i="".concat(i.slice(0,128),"...")),"The argument '".concat(e,"' ").concat(n,". Received ").concat(i)}),TypeError,RangeError),u("ERR_INVALID_RETURN_VALUE",(function(e,t,r){var i;return i=r&&r.constructor&&r.constructor.name?"instance of ".concat(r.constructor.name):"type ".concat(n(r)),"Expected ".concat(e,' to be returned from the "').concat(t,'"')+" function but got ".concat(i,".")}),TypeError),u("ERR_MISSING_ARGS",(function(){for(var e=arguments.length,t=new Array(e),n=0;n0,"At least one arg needs to be specified");var i="The ",o=t.length;switch(t=t.map((function(e){return'"'.concat(e,'"')})),o){case 1:i+="".concat(t[0]," argument");break;case 2:i+="".concat(t[0]," and ").concat(t[1]," arguments");break;default:i+=t.slice(0,o-1).join(", "),i+=", and ".concat(t[o-1]," arguments")}return"".concat(i," must be specified")}),TypeError),e.exports.codes=c},19158:(e,t,r)=>{"use strict";function n(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=[],n=!0,i=!1,o=void 0;try{for(var a,s=e[Symbol.iterator]();!(n=(a=s.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(e){i=!0,o=e}finally{try{n||null==s.return||s.return()}finally{if(i)throw o}}return r}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}var o=void 0!==/a/g.flags,a=function(e){var t=[];return e.forEach((function(e){return t.push(e)})),t},s=function(e){var t=[];return e.forEach((function(e,r){return t.push([r,e])})),t},c=Object.is?Object.is:r(20609),u=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols:function(){return[]},l=Number.isNaN?Number.isNaN:r(20360);function d(e){return e.call.bind(e)}var f=d(Object.prototype.hasOwnProperty),h=d(Object.prototype.propertyIsEnumerable),p=d(Object.prototype.toString),g=r(89539).types,m=g.isAnyArrayBuffer,y=g.isArrayBufferView,b=g.isDate,v=g.isMap,w=g.isRegExp,_=g.isSet,E=g.isNativeError,S=g.isBoxedPrimitive,T=g.isNumberObject,A=g.isStringObject,I=g.isBooleanObject,x=g.isBigIntObject,O=g.isSymbolObject,k=g.isFloat32Array,P=g.isFloat64Array;function C(e){if(0===e.length||e.length>10)return!0;for(var t=0;t57)return!0}return 10===e.length&&e>=Math.pow(2,32)}function N(e){return Object.keys(e).filter(C).concat(u(e).filter(Object.prototype.propertyIsEnumerable.bind(e)))}function M(e,t){if(e===t)return 0;for(var r=e.length,n=t.length,i=0,o=Math.min(r,n);i{"use strict";e.exports=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r>>0,u=new Uint8Array(o);e[r];){var l=t[e.charCodeAt(r)];if(255===l)return;for(var d=0,f=o-1;(0!==l||d>>0,u[f]=l%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");i=d,r++}for(var h=o-i;h!==o&&0===u[h];)h++;for(var p=new Uint8Array(n+(o-h)),g=n;h!==o;)p[g++]=u[h++];return p}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,i=0,o=t.length;i!==o&&0===t[i];)i++,r++;for(var c=(o-i)*u+1>>>0,l=new Uint8Array(c);i!==o;){for(var d=t[i],f=0,h=c-1;(0!==d||f>>0,l[h]=d%a>>>0,d=d/a>>>0;if(0!==d)throw new Error("Non-zero carry");n=f,i++}for(var p=c-n;p!==c&&0===l[p];)p++;for(var g=s.repeat(r);p{var n=r(48764).Buffer,i=r(34155);!function(){var t,o,a="0123456789abcdefghjkmnpqrtuvwxyz",s={o:0,i:1,l:1,s:5},c=function(){for(var e={},t=0;t>-e:t=r<3?(e-=8,1):(e<4&&(this.output+=a[t>>3],e+=5),0)},this.finish=function(r){var n=this.output+(e<0?a[t>>3]:"")+(r?"$":"");return this.output="",n}}function l(){var e=0,t=0;this.output="",this.readChar=function(r){"string"!=typeof r&&"number"==typeof r&&(r=String.fromCharCode(r)),r=r.toLowerCase();var n=c()[r];void 0!==n&&(t|=(n<<=3)>>>e,(e+=5)>=8&&(this.output+=String.fromCharCode(t),t=(e-=8)>0?n<<5-e&255:0))},this.finish=function(t){var r=this.output+(e<0?a[bits>>3]:"")+(t?"$":"");return this.output="",r}}function d(e){return(new u).update(e,!0)}function f(e,i){void 0===t&&(t=r(55835));var o,a=t.createHash("sha1");if(a.digest=(o=a.digest,function(){return d(o.call(this,"binary"))}),i){if("string"==typeof e||n.isBuffer(e))try{return i(null,f(e))}catch(e){return i(e,null)}return"function"==(e.on,!1)?i({message:"Not a stream!"}):(e.on("data",(function(e){a.update(e)})),void e.on("end",(function(){i(null,a.digest())})))}return e?a.update(e).digest():a}u.prototype.update=function(e,t){for(var r=0;r{"use strict";t.byteLength=function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,o=c(e),a=o[0],s=o[1],u=new i(function(e,t,r){return 3*(t+r)/4-r}(0,a,s)),l=0,d=s>0?a-4:a;for(r=0;r>16&255,u[l++]=t>>8&255,u[l++]=255&t;return 2===s&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,u[l++]=255&t),1===s&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t),u},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,o=[],a=16383,s=0,c=n-i;sc?c:s+a));return 1===i?(t=e[n-1],o.push(r[t>>2]+r[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],o.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),o.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,s=o.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,n){for(var i,o,a=[],s=t;s>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return a.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},27715:(e,t)=>{"use strict";t.gW=void 0;const r="qpzry9x8gf2tvdw0s3jn54khce6mua7l",n={};for(let e=0;e>25;return(33554431&e)<<5^996825010&-(t>>0&1)^642813549&-(t>>1&1)^513874426&-(t>>2&1)^1027748829&-(t>>3&1)^705979059&-(t>>4&1)}function o(e){let t=1;for(let r=0;r126)return"Invalid prefix ("+e+")";t=i(t)^n>>5}t=i(t);for(let r=0;r=r;)o-=r,s.push(i>>o&a);if(n)o>0&&s.push(i<=t)return"Excess padding";if(i<r)return"Exceeds length limit";const a=e.toLowerCase(),s=e.toUpperCase();if(e!==a&&e!==s)return"Mixed-case string "+e;const c=(e=a).lastIndexOf("1");if(-1===c)return"No separator character for "+e;if(0===c)return"Missing prefix for "+e;const u=e.slice(0,c),l=e.slice(c+1);if(l.length<6)return"Data too short";let d=o(u);if("string"==typeof d)return d;const f=[];for(let e=0;e=l.length||f.push(r)}return d!==t?"Invalid checksum for "+e:{prefix:u,words:f}}return t="bech32"===e?1:734539939,{decodeUnsafe:function(e,t){const r=a(e,t);if("object"==typeof r)return r},decode:function(e,t){const r=a(e,t);if("object"==typeof r)return r;throw new Error(r)},encode:function(e,n,a){if(a=a||90,e.length+7+n.length>a)throw new TypeError("Exceeds length limit");let s=o(e=e.toLowerCase());if("string"==typeof s)throw new Error(s);let c=e+"1";for(let e=0;e>5!=0)throw new Error("Non 5-bit word");s=i(s)^t,c+=r.charAt(t)}for(let e=0;e<6;++e)s=i(s);s^=t;for(let e=0;e<6;++e)c+=r.charAt(s>>5*(5-e)&31);return c},toWords:s,fromWordsUnsafe:c,fromWords:u}}t.gW=l("bech32"),l("bech32m")},51409:(e,t)=>{!function(e){"use strict";var t={};function r(e,n,o){if(o!==t)return e instanceof r?e:void 0===e?i:r.parse(e);for(e=e||[];e.length&&!e[e.length-1];)--e.length;this._d=e,this._s=e.length?n||1:0}r._construct=function(e,n){return new r(e,n,t)};var n=1e7;r.base=n,r.base_log10=7;var i=new r([],0,t);r.ZERO=i;var o=new r([1],1,t);r.ONE=o;var a=new r(o._d,-1,t);r.M_ONE=a,r._0=i,r._1=o,r.small=[i,o,new r([2],1,t),new r([3],1,t),new r([4],1,t),new r([5],1,t),new r([6],1,t),new r([7],1,t),new r([8],1,t),new r([9],1,t),new r([10],1,t),new r([11],1,t),new r([12],1,t),new r([13],1,t),new r([14],1,t),new r([15],1,t),new r([16],1,t),new r([17],1,t),new r([18],1,t),new r([19],1,t),new r([20],1,t),new r([21],1,t),new r([22],1,t),new r([23],1,t),new r([24],1,t),new r([25],1,t),new r([26],1,t),new r([27],1,t),new r([28],1,t),new r([29],1,t),new r([30],1,t),new r([31],1,t),new r([32],1,t),new r([33],1,t),new r([34],1,t),new r([35],1,t),new r([36],1,t)],r.digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),r.prototype.toString=function(e){if((e=+e||10)<2||e>36)throw new Error("illegal radix "+e+".");if(0===this._s)return"0";if(10===e){var t=this._s<0?"-":"";t+=this._d[this._d.length-1].toString();for(var n=this._d.length-2;n>=0;n--){for(var i=this._d[n].toString();i.length<7;)i="0"+i;t+=i}return t}var o=r.digits;e=r.small[e];for(var a,s=this._s,c=this.abs(),u=[];0!==c._s;){var l=c.divRem(e);c=l[0],a=l[1],u.push(o[a.valueOf()])}return(s<0?"-":"")+u.reverse().join("")},r.radixRegex=[/^$/,/^$/,/^[01]*$/,/^[012]*$/,/^[0-3]*$/,/^[0-4]*$/,/^[0-5]*$/,/^[0-6]*$/,/^[0-7]*$/,/^[0-8]*$/,/^[0-9]*$/,/^[0-9aA]*$/,/^[0-9abAB]*$/,/^[0-9abcABC]*$/,/^[0-9a-dA-D]*$/,/^[0-9a-eA-E]*$/,/^[0-9a-fA-F]*$/,/^[0-9a-gA-G]*$/,/^[0-9a-hA-H]*$/,/^[0-9a-iA-I]*$/,/^[0-9a-jA-J]*$/,/^[0-9a-kA-K]*$/,/^[0-9a-lA-L]*$/,/^[0-9a-mA-M]*$/,/^[0-9a-nA-N]*$/,/^[0-9a-oA-O]*$/,/^[0-9a-pA-P]*$/,/^[0-9a-qA-Q]*$/,/^[0-9a-rA-R]*$/,/^[0-9a-sA-S]*$/,/^[0-9a-tA-T]*$/,/^[0-9a-uA-U]*$/,/^[0-9a-vA-V]*$/,/^[0-9a-wA-W]*$/,/^[0-9a-xA-X]*$/,/^[0-9a-yA-Y]*$/,/^[0-9a-zA-Z]*$/],r.parse=function(e,n){e=e.toString(),void 0!==n&&10!=+n||(e=e.replace(/\s*[*xX]\s*10\s*(\^|\*\*)\s*/,"e").replace(/^([+\-])?(\d+)\.?(\d*)[eE]([+\-]?\d+)$/,(function(e,t,r,n,i){var o=(i=+i)<0,a=r.length+i;e=(o?r:n).length,i=(i=Math.abs(i))>=e?i-e+o:0;var s=new Array(i+1).join("0"),c=r+n;return(t||"")+(o?c=s+c:c+=s).substr(0,a+=o?s.length:0)+(a36)throw new Error("Illegal radix "+n+".");if(n=+n,!r.radixRegex[n].test(c))throw new Error("Bad digit for radix "+n);if(0===(c=c.replace(/^0+/,"").split("")).length)return i;if(a="-"===a?-1:1,10==n){for(var u=[];c.length>=7;)u.push(parseInt(c.splice(c.length-r.base_log10,r.base_log10).join(""),10));return u.push(parseInt(c.join(""),10)),new r(u,a,t)}u=i,n=r.small[n];for(var l=r.small,d=0;ds&&(o=a,s=c),f=l;d&&fn)return 1;for(var i=this._d,o=e._d,a=t-1;a>=0;a--)if(i[a]!==o[a])return i[a]=e._d.length,s=(a?this:e)._d,c=(a?e:this)._d,u=s.length,l=c.length,d=u+l,f=new Array(d);for(o=0;o=n?[o%n|0,o/n|0]:[o],1,t);if(2===e)return this.add(this);if(this.isUnit())return new r([e],1,t);for(var a=this._d,s=a.length,c=s+1,u=new Array(c),l=0;lu._d.length&&(m=(m+1)*n),s=Math.ceil(m/y)}do{var b=u.multiplySingleDigit(s);if(b.compareAbs(h)<=0)break;s--}while(s);if(f.push(s),s){var v=h.subtract(b);h._d=v._d.slice(),0===h._d.length&&(h._s=0)}}return[new r(f.reverse(),c,t),new r(h._d,this._s,t)]},r.prototype.divRemSmall=function(e){var o;if(0==(e=+e))throw new Error("Divide by zero");var a=e<0?-1:1,s=this._s*a;if((e=Math.abs(e))<1||e>=n)throw new Error("Argument out of range");if(0===this._s)return[i,i];if(1===e||-1===e)return[1===s?this.abs():new r(this._d,s,t),i];if(1===this._d.length){var c=new r([this._d[0]/e|0],1,t);return o=new r([this._d[0]%e|0],1,t),s<0&&(c=c.negate()),this._s<0&&(o=o.negate()),[c,o]}for(var u,l=this._d.slice(),d=new Array(l.length),f=0,h=0,p=0;l.length;)(f=f*n+l[l.length-1])0},r.prototype.isNegative=function(){return this._s<0},r.prototype.isZero=function(){return 0===this._s},r.prototype.exp10=function(e){if(0==(e=+e))return this;if(Math.abs(e)>Number(s))throw new Error("exponent too large in BigInteger.exp10");if(e>0){for(var n=new r(this._d.slice(),this._s,t);e>=7;e-=7)n._d.unshift(0);return 0==e?n:(n._s=1,n=n.multiplySingleDigit(Math.pow(10,e)),this._s<0?n.negate():n)}if(-e>=7*this._d.length)return i;for(n=new r(this._d.slice(),this._s,t),e=-e;e>=7;e-=7)n._d.shift();return 0==e?n:n.divRemSmall(Math.pow(10,e))[0]},r.prototype.pow=function(e){if(this.isUnit())return this._s>0||r(e).isOdd()?this:this.negate();if(0===(e=r(e))._s)return o;if(e._s<0){if(0===this._s)throw new Error("Divide by zero");return i}if(0===this._s)return i;if(e.isUnit())return this;if(e.compareAbs(s)>0)throw new Error("exponent too large in BigInteger.pow");for(var t=this,n=o,a=r.small[2];e.isPositive();){if(e.isOdd()&&(n=n.multiply(t),e.isUnit()))return n;t=t.square(),e=e.quotient(a)}return n},r.prototype.modPow=function(e,t){for(var n=o,i=this;e.isPositive();)e.isOdd()&&(n=n.multiply(i).remainder(t)),(e=e.quotient(r.small[2])).isPositive()&&(i=i.square().remainder(t));return n},r.prototype.log=function(){switch(this._s){case 0:return-1/0;case-1:return NaN}var e=this._d.length;if(7*e<30)return Math.log(this.valueOf());var i=Math.ceil(30/7),o=this._d.slice(e-i);return Math.log(new r(o,1,t).valueOf())+(e-i)*Math.log(n)},r.prototype.valueOf=function(){return parseInt(this.toString(),10)},r.prototype.toJSValue=function(){return parseInt(this.toString(),10)};var s=r(2147483647);r.MAX_EXP=s,function(){function e(e){return function(t){return e.call(r(t))}}function t(e){return function(t,n){return e.call(r(t),r(n))}}function n(e){return function(t,n,i){return e.call(r(t),r(n),r(i))}}!function(){var i,o,a="toJSValue,isEven,isOdd,sign,isZero,isNegative,abs,isUnit,square,negate,isPositive,toString,next,prev,log".split(","),s="compare,remainder,divRem,subtract,add,quotient,divide,multiply,pow,compareAbs".split(","),c=["modPow"];for(i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(36574);function i(e,t,r){return n=>{if(e.has(n))return;const i=r.filter((e=>e.key.toString("hex")===n))[0];t.push(i),e.add(n)}}function o(e){return e.globalMap.unsignedTx}function a(e){const t=new Set;return e.forEach((e=>{const r=e.key.toString("hex");if(t.has(r))throw new Error("Combine: KeyValue Map keys should be unique");t.add(r)})),t}t.combine=function(e){const t=e[0],r=n.psbtToKeyVals(t),s=e.slice(1);if(0===s.length)throw new Error("Combine: Nothing to combine");const c=o(t);if(void 0===c)throw new Error("Combine: Self missing transaction");const u=a(r.globalKeyVals),l=r.inputKeyVals.map(a),d=r.outputKeyVals.map(a);for(const e of s){const t=o(e);if(void 0===t||!t.toBuffer().equals(c.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const s=n.psbtToKeyVals(e);a(s.globalKeyVals).forEach(i(u,r.globalKeyVals,s.globalKeyVals)),s.inputKeyVals.map(a).forEach(((e,t)=>e.forEach(i(l[t],r.inputKeyVals[t],s.inputKeyVals[t])))),s.outputKeyVals.map(a).forEach(((e,t)=>e.forEach(i(d[t],r.outputKeyVals[t],s.outputKeyVals[t]))))}return n.psbtFromKeyVals(c,{globalMapKeyVals:r.globalKeyVals,inputKeyVals:r.inputKeyVals,outputKeyVals:r.outputKeyVals})}},44041:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(1847);t.decode=function(e){if(e.key[0]!==i.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+e.key.toString("hex"));if(79!==e.key.length||![2,3].includes(e.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+e.key.toString("hex"));if(e.value.length/4%1!=0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const t=e.key.slice(1),r={masterFingerprint:e.value.slice(0,4),extendedPubkey:t,path:"m"};for(const t of(n=e.value.length/4-1,[...Array(n).keys()])){const n=e.value.readUInt32LE(4*t+4),i=!!(2147483648&n),o=2147483647&n;r.path+="/"+o.toString(10)+(i?"'":"")}var n;return r},t.encode=function(e){const t=n.from([i.GlobalTypes.GLOBAL_XPUB]),r=n.concat([t,e.extendedPubkey]),o=e.path.split("/"),a=n.allocUnsafe(4*o.length);e.masterFingerprint.copy(a,0);let s=4;return o.slice(1).forEach((e=>{const t="'"===e.slice(-1);let r=2147483647&parseInt(t?e.slice(0,-1):e,10);t&&(r+=2147483648),a.writeUInt32LE(r,s),s+=4})),{key:r,value:a}},t.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }",t.check=function(e){const t=e.extendedPubkey,r=e.masterFingerprint,i=e.path;return n.isBuffer(t)&&78===t.length&&[2,3].indexOf(t[45])>-1&&n.isBuffer(r)&&4===r.length&&"string"==typeof i&&!!i.match(/^m(\/\d+'?)*$/)},t.canAddToArray=function(e,t,r){const n=t.extendedPubkey.toString("hex");return!r.has(n)&&(r.add(n),0===e.filter((e=>e.extendedPubkey.equals(t.extendedPubkey))).length)}},74480:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(1847);t.encode=function(e){return{key:n.from([i.GlobalTypes.UNSIGNED_TX]),value:e.toBuffer()}}},71528:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(1847),i=r(44041),o=r(74480),a=r(20859),s=r(8248),c=r(70537),u=r(61511),l=r(65896),d=r(91243),f=r(3530),h=r(49265),p=r(23934),g=r(50602),m=r(82954),y=r(6036),b=r(44799),v=r(99595),w=r(9705),_=r(17196),E=r(29375),S=r(66327),T={unsignedTx:o,globalXpub:i,checkPubkey:v.makeChecker([])};t.globals=T;const A={nonWitnessUtxo:c,partialSig:u,sighashType:d,finalScriptSig:a,finalScriptWitness:s,porCommitment:l,witnessUtxo:m,bip32Derivation:b.makeConverter(n.InputTypes.BIP32_DERIVATION),redeemScript:w.makeConverter(n.InputTypes.REDEEM_SCRIPT),witnessScript:S.makeConverter(n.InputTypes.WITNESS_SCRIPT),checkPubkey:v.makeChecker([n.InputTypes.PARTIAL_SIG,n.InputTypes.BIP32_DERIVATION]),tapKeySig:f,tapScriptSig:g,tapLeafScript:h,tapBip32Derivation:_.makeConverter(n.InputTypes.TAP_BIP32_DERIVATION),tapInternalKey:E.makeConverter(n.InputTypes.TAP_INTERNAL_KEY),tapMerkleRoot:p};t.inputs=A;const I={bip32Derivation:b.makeConverter(n.OutputTypes.BIP32_DERIVATION),redeemScript:w.makeConverter(n.OutputTypes.REDEEM_SCRIPT),witnessScript:S.makeConverter(n.OutputTypes.WITNESS_SCRIPT),checkPubkey:v.makeChecker([n.OutputTypes.BIP32_DERIVATION]),tapBip32Derivation:_.makeConverter(n.OutputTypes.TAP_BIP32_DERIVATION),tapTree:y,tapInternalKey:E.makeConverter(n.OutputTypes.TAP_INTERNAL_KEY)};t.outputs=I},20859:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(1847);t.decode=function(e){if(e.key[0]!==i.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+e.key.toString("hex"));return e.value},t.encode=function(e){return{key:n.from([i.InputTypes.FINAL_SCRIPTSIG]),value:e}},t.expected="Buffer",t.check=function(e){return n.isBuffer(e)},t.canAdd=function(e,t){return!!e&&!!t&&void 0===e.finalScriptSig}},8248:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(1847);t.decode=function(e){if(e.key[0]!==i.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+e.key.toString("hex"));return e.value},t.encode=function(e){return{key:n.from([i.InputTypes.FINAL_SCRIPTWITNESS]),value:e}},t.expected="Buffer",t.check=function(e){return n.isBuffer(e)},t.canAdd=function(e,t){return!!e&&!!t&&void 0===e.finalScriptWitness}},70537:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(1847);t.decode=function(e){if(e.key[0]!==i.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+e.key.toString("hex"));return e.value},t.encode=function(e){return{key:n.from([i.InputTypes.NON_WITNESS_UTXO]),value:e}},t.expected="Buffer",t.check=function(e){return n.isBuffer(e)},t.canAdd=function(e,t){return!!e&&!!t&&void 0===e.nonWitnessUtxo}},61511:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(1847);t.decode=function(e){if(e.key[0]!==i.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+e.key.toString("hex"));if(34!==e.key.length&&66!==e.key.length||![2,3,4].includes(e.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+e.key.toString("hex"));return{pubkey:e.key.slice(1),signature:e.value}},t.encode=function(e){const t=n.from([i.InputTypes.PARTIAL_SIG]);return{key:n.concat([t,e.pubkey]),value:e.signature}},t.expected="{ pubkey: Buffer; signature: Buffer; }",t.check=function(e){return n.isBuffer(e.pubkey)&&n.isBuffer(e.signature)&&[33,65].includes(e.pubkey.length)&&[2,3,4].includes(e.pubkey[0])&&function(e){if(!n.isBuffer(e)||e.length<9)return!1;if(48!==e[0])return!1;if(e.length!==e[1]+3)return!1;if(2!==e[2])return!1;const t=e[3];if(t>33||t<1)return!1;if(2!==e[3+t+1])return!1;const r=e[3+t+2];return!(r>33||r<1)&&e.length===3+t+2+r+2}(e.signature)},t.canAddToArray=function(e,t,r){const n=t.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===e.filter((e=>e.pubkey.equals(t.pubkey))).length)}},65896:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(1847);t.decode=function(e){if(e.key[0]!==i.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+e.key.toString("hex"));return e.value.toString("utf8")},t.encode=function(e){return{key:n.from([i.InputTypes.POR_COMMITMENT]),value:n.from(e,"utf8")}},t.expected="string",t.check=function(e){return"string"==typeof e},t.canAdd=function(e,t){return!!e&&!!t&&void 0===e.porCommitment}},91243:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(1847);t.decode=function(e){if(e.key[0]!==i.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+e.key.toString("hex"));return e.value.readUInt32LE(0)},t.encode=function(e){const t=n.from([i.InputTypes.SIGHASH_TYPE]),r=n.allocUnsafe(4);return r.writeUInt32LE(e,0),{key:t,value:r}},t.expected="number",t.check=function(e){return"number"==typeof e},t.canAdd=function(e,t){return!!e&&!!t&&void 0===e.sighashType}},3530:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(1847);function o(e){return n.isBuffer(e)&&(64===e.length||65===e.length)}t.decode=function(e){if(e.key[0]!==i.InputTypes.TAP_KEY_SIG||1!==e.key.length)throw new Error("Decode Error: could not decode tapKeySig with key 0x"+e.key.toString("hex"));if(!o(e.value))throw new Error("Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature");return e.value},t.encode=function(e){return{key:n.from([i.InputTypes.TAP_KEY_SIG]),value:e}},t.expected="Buffer",t.check=o,t.canAdd=function(e,t){return!!e&&!!t&&void 0===e.tapKeySig}},49265:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(1847);t.decode=function(e){if(e.key[0]!==i.InputTypes.TAP_LEAF_SCRIPT)throw new Error("Decode Error: could not decode tapLeafScript with key 0x"+e.key.toString("hex"));if((e.key.length-2)%32!=0)throw new Error("Decode Error: tapLeafScript has invalid control block in key 0x"+e.key.toString("hex"));const t=e.value[e.value.length-1];if((254&e.key[1])!==t)throw new Error("Decode Error: tapLeafScript bad leaf version in key 0x"+e.key.toString("hex"));const r=e.value.slice(0,-1);return{controlBlock:e.key.slice(1),script:r,leafVersion:t}},t.encode=function(e){const t=n.from([i.InputTypes.TAP_LEAF_SCRIPT]),r=n.from([e.leafVersion]);return{key:n.concat([t,e.controlBlock]),value:n.concat([e.script,r])}},t.expected="{ controlBlock: Buffer; leafVersion: number, script: Buffer; }",t.check=function(e){return n.isBuffer(e.controlBlock)&&(e.controlBlock.length-1)%32==0&&(254&e.controlBlock[0])===e.leafVersion&&n.isBuffer(e.script)},t.canAddToArray=function(e,t,r){const n=t.controlBlock.toString("hex");return!r.has(n)&&(r.add(n),0===e.filter((e=>e.controlBlock.equals(t.controlBlock))).length)}},23934:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(1847);function o(e){return n.isBuffer(e)&&32===e.length}t.decode=function(e){if(e.key[0]!==i.InputTypes.TAP_MERKLE_ROOT||1!==e.key.length)throw new Error("Decode Error: could not decode tapMerkleRoot with key 0x"+e.key.toString("hex"));if(!o(e.value))throw new Error("Decode Error: tapMerkleRoot not a 32-byte hash");return e.value},t.encode=function(e){return{key:n.from([i.InputTypes.TAP_MERKLE_ROOT]),value:e}},t.expected="Buffer",t.check=o,t.canAdd=function(e,t){return!!e&&!!t&&void 0===e.tapMerkleRoot}},50602:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(1847);t.decode=function(e){if(e.key[0]!==i.InputTypes.TAP_SCRIPT_SIG)throw new Error("Decode Error: could not decode tapScriptSig with key 0x"+e.key.toString("hex"));if(65!==e.key.length)throw new Error("Decode Error: tapScriptSig has invalid key 0x"+e.key.toString("hex"));if(64!==e.value.length&&65!==e.value.length)throw new Error("Decode Error: tapScriptSig has invalid signature in key 0x"+e.key.toString("hex"));return{pubkey:e.key.slice(1,33),leafHash:e.key.slice(33),signature:e.value}},t.encode=function(e){const t=n.from([i.InputTypes.TAP_SCRIPT_SIG]);return{key:n.concat([t,e.pubkey,e.leafHash]),value:e.signature}},t.expected="{ pubkey: Buffer; leafHash: Buffer; signature: Buffer; }",t.check=function(e){return n.isBuffer(e.pubkey)&&n.isBuffer(e.leafHash)&&n.isBuffer(e.signature)&&32===e.pubkey.length&&32===e.leafHash.length&&(64===e.signature.length||65===e.signature.length)},t.canAddToArray=function(e,t,r){const n=t.pubkey.toString("hex")+t.leafHash.toString("hex");return!r.has(n)&&(r.add(n),0===e.filter((e=>e.pubkey.equals(t.pubkey)&&e.leafHash.equals(t.leafHash))).length)}},82954:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(1847),o=r(19254),a=r(3493);t.decode=function(e){if(e.key[0]!==i.InputTypes.WITNESS_UTXO)throw new Error("Decode Error: could not decode witnessUtxo with key 0x"+e.key.toString("hex"));const t=o.readUInt64LE(e.value,0);let r=8;const n=a.decode(e.value,r);r+=a.encodingLength(n);const s=e.value.slice(r);if(s.length!==n)throw new Error("Decode Error: WITNESS_UTXO script is not proper length");return{script:s,value:t}},t.encode=function(e){const{script:t,value:r}=e,s=a.encodingLength(t.length),c=n.allocUnsafe(8+s+t.length);return o.writeUInt64LE(c,r,0),a.encode(t.length,c,8),t.copy(c,8+s),{key:n.from([i.InputTypes.WITNESS_UTXO]),value:c}},t.expected="{ script: Buffer; value: number; }",t.check=function(e){return n.isBuffer(e.script)&&"number"==typeof e.value},t.canAdd=function(e,t){return!!e&&!!t&&void 0===e.witnessUtxo}},6036:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(1847),o=r(3493);t.decode=function(e){if(e.key[0]!==i.OutputTypes.TAP_TREE||1!==e.key.length)throw new Error("Decode Error: could not decode tapTree with key 0x"+e.key.toString("hex"));let t=0;const r=[];for(;t[n.of(e.depth,e.leafVersion),o.encode(e.script.length),e.script])));return{key:t,value:n.concat(r)}},t.expected="{ leaves: [{ depth: number; leafVersion: number, script: Buffer; }] }",t.check=function(e){return Array.isArray(e.leaves)&&e.leaves.every((e=>e.depth>=0&&e.depth<=128&&(254&e.leafVersion)===e.leafVersion&&n.isBuffer(e.script)))},t.canAdd=function(e,t){return!!e&&!!t&&void 0===e.tapTree}},44799:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=e=>33===e.length&&[2,3].includes(e[0])||65===e.length&&4===e[0];t.makeConverter=function(e,t=i){return{decode:function(r){if(r.key[0]!==e)throw new Error("Decode Error: could not decode bip32Derivation with key 0x"+r.key.toString("hex"));const n=r.key.slice(1);if(!t(n))throw new Error("Decode Error: bip32Derivation has invalid pubkey in key 0x"+r.key.toString("hex"));if(r.value.length/4%1!=0)throw new Error("Decode Error: Input BIP32_DERIVATION value length should be multiple of 4");const i={masterFingerprint:r.value.slice(0,4),pubkey:n,path:"m"};for(const e of(o=r.value.length/4-1,[...Array(o).keys()])){const t=r.value.readUInt32LE(4*e+4),n=!!(2147483648&t),o=2147483647&t;i.path+="/"+o.toString(10)+(n?"'":"")}var o;return i},encode:function(t){const r=n.from([e]),i=n.concat([r,t.pubkey]),o=t.path.split("/"),a=n.allocUnsafe(4*o.length);t.masterFingerprint.copy(a,0);let s=4;return o.slice(1).forEach((e=>{const t="'"===e.slice(-1);let r=2147483647&parseInt(t?e.slice(0,-1):e,10);t&&(r+=2147483648),a.writeUInt32LE(r,s),s+=4})),{key:i,value:a}},check:function(e){return n.isBuffer(e.pubkey)&&n.isBuffer(e.masterFingerprint)&&"string"==typeof e.path&&t(e.pubkey)&&4===e.masterFingerprint.length},expected:"{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }",canAddToArray:function(e,t,r){const n=t.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===e.filter((e=>e.pubkey.equals(t.pubkey))).length)}}}},99595:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.makeChecker=function(e){return function(t){let r;if(e.includes(t.key[0])&&(r=t.key.slice(1),33!==r.length&&65!==r.length||![2,3,4].includes(r[0])))throw new Error("Format Error: invalid pubkey in key 0x"+t.key.toString("hex"));return r}}},9705:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.makeConverter=function(e){return{decode:function(t){if(t.key[0]!==e)throw new Error("Decode Error: could not decode redeemScript with key 0x"+t.key.toString("hex"));return t.value},encode:function(t){return{key:n.from([e]),value:t}},check:function(e){return n.isBuffer(e)},expected:"Buffer",canAdd:function(e,t){return!!e&&!!t&&void 0===e.redeemScript}}}},17196:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(3493),o=r(44799),a=e=>32===e.length;t.makeConverter=function(e){const t=o.makeConverter(e,a);return{decode:function(e){const r=i.decode(e.value),n=i.encodingLength(r),o=t.decode({key:e.key,value:e.value.slice(n+32*r)}),a=new Array(r);for(let t=0,i=n;tn.isBuffer(e)&&32===e.length))&&t.check(e)},expected:"{ masterFingerprint: Buffer; pubkey: Buffer; path: string; leafHashes: Buffer[]; }",canAddToArray:t.canAddToArray}}},29375:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.makeConverter=function(e){return{decode:function(t){if(t.key[0]!==e||1!==t.key.length)throw new Error("Decode Error: could not decode tapInternalKey with key 0x"+t.key.toString("hex"));if(32!==t.value.length)throw new Error("Decode Error: tapInternalKey not a 32-byte x-only pubkey");return t.value},encode:function(t){return{key:n.from([e]),value:t}},check:function(e){return n.isBuffer(e)&&32===e.length},expected:"Buffer",canAdd:function(e,t){return!!e&&!!t&&void 0===e.tapInternalKey}}}},66327:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.makeConverter=function(e){return{decode:function(t){if(t.key[0]!==e)throw new Error("Decode Error: could not decode witnessScript with key 0x"+t.key.toString("hex"));return t.value},encode:function(t){return{key:n.from([e]),value:t}},check:function(e){return n.isBuffer(e)},expected:"Buffer",canAdd:function(e,t){return!!e&&!!t&&void 0===e.witnessScript}}}},19254:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(3493);function o(e){const t=e.key.length,r=e.value.length,o=i.encodingLength(t),a=i.encodingLength(r),s=n.allocUnsafe(o+t+a+r);return i.encode(t,s,0),e.key.copy(s,o),i.encode(r,s,o+t),e.value.copy(s,o+t+a),s}function a(e,t){if("number"!=typeof e)throw new Error("cannot write a non-number as a number");if(e<0)throw new Error("specified a negative value for writing an unsigned value");if(e>t)throw new Error("RangeError: value out of range");if(Math.floor(e)!==e)throw new Error("value has a fractional component")}t.range=e=>[...Array(e).keys()],t.reverseBuffer=function(e){if(e.length<1)return e;let t=e.length-1,r=0;for(let n=0;n{"use strict";var n=r(48764).Buffer;function i(e){if(e<0||e>9007199254740991||e%1!=0)throw new RangeError("value out of range")}function o(e){return i(e),e<253?1:e<=65535?3:e<=4294967295?5:9}Object.defineProperty(t,"__esModule",{value:!0}),t.encode=function e(t,r,a){if(i(t),r||(r=n.allocUnsafe(o(t))),!n.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return a||(a=0),t<253?(r.writeUInt8(t,a),Object.assign(e,{bytes:1})):t<=65535?(r.writeUInt8(253,a),r.writeUInt16LE(t,a+1),Object.assign(e,{bytes:3})):t<=4294967295?(r.writeUInt8(254,a),r.writeUInt32LE(t,a+1),Object.assign(e,{bytes:5})):(r.writeUInt8(255,a),r.writeUInt32LE(t>>>0,a+1),r.writeUInt32LE(t/4294967296|0,a+5),Object.assign(e,{bytes:9})),r},t.decode=function e(t,r){if(!n.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");r||(r=0);const o=t.readUInt8(r);if(o<253)return Object.assign(e,{bytes:1}),o;if(253===o)return Object.assign(e,{bytes:3}),t.readUInt16LE(r+1);if(254===o)return Object.assign(e,{bytes:5}),t.readUInt32LE(r+1);{Object.assign(e,{bytes:9});const n=t.readUInt32LE(r+1),o=4294967296*t.readUInt32LE(r+5)+n;return i(o),o}},t.encodingLength=o},12974:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(71528),o=r(19254),a=r(3493),s=r(1847);function c(e,t,r){if(!t.equals(n.from([r])))throw new Error(`Format Error: Invalid ${e} key: ${t.toString("hex")}`)}function u(e,{globalMapKeyVals:t,inputKeyVals:r,outputKeyVals:n}){const a={unsignedTx:e};let u=0;for(const e of t)switch(e.key[0]){case s.GlobalTypes.UNSIGNED_TX:if(c("global",e.key,s.GlobalTypes.UNSIGNED_TX),u>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");u++;break;case s.GlobalTypes.GLOBAL_XPUB:void 0===a.globalXpub&&(a.globalXpub=[]),a.globalXpub.push(i.globals.globalXpub.decode(e));break;default:a.unknownKeyVals||(a.unknownKeyVals=[]),a.unknownKeyVals.push(e)}const l=r.length,d=n.length,f=[],h=[];for(const e of o.range(l)){const t={};for(const n of r[e])switch(i.inputs.checkPubkey(n),n.key[0]){case s.InputTypes.NON_WITNESS_UTXO:if(c("input",n.key,s.InputTypes.NON_WITNESS_UTXO),void 0!==t.nonWitnessUtxo)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");t.nonWitnessUtxo=i.inputs.nonWitnessUtxo.decode(n);break;case s.InputTypes.WITNESS_UTXO:if(c("input",n.key,s.InputTypes.WITNESS_UTXO),void 0!==t.witnessUtxo)throw new Error("Format Error: Input has multiple WITNESS_UTXO");t.witnessUtxo=i.inputs.witnessUtxo.decode(n);break;case s.InputTypes.PARTIAL_SIG:void 0===t.partialSig&&(t.partialSig=[]),t.partialSig.push(i.inputs.partialSig.decode(n));break;case s.InputTypes.SIGHASH_TYPE:if(c("input",n.key,s.InputTypes.SIGHASH_TYPE),void 0!==t.sighashType)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");t.sighashType=i.inputs.sighashType.decode(n);break;case s.InputTypes.REDEEM_SCRIPT:if(c("input",n.key,s.InputTypes.REDEEM_SCRIPT),void 0!==t.redeemScript)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");t.redeemScript=i.inputs.redeemScript.decode(n);break;case s.InputTypes.WITNESS_SCRIPT:if(c("input",n.key,s.InputTypes.WITNESS_SCRIPT),void 0!==t.witnessScript)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");t.witnessScript=i.inputs.witnessScript.decode(n);break;case s.InputTypes.BIP32_DERIVATION:void 0===t.bip32Derivation&&(t.bip32Derivation=[]),t.bip32Derivation.push(i.inputs.bip32Derivation.decode(n));break;case s.InputTypes.FINAL_SCRIPTSIG:c("input",n.key,s.InputTypes.FINAL_SCRIPTSIG),t.finalScriptSig=i.inputs.finalScriptSig.decode(n);break;case s.InputTypes.FINAL_SCRIPTWITNESS:c("input",n.key,s.InputTypes.FINAL_SCRIPTWITNESS),t.finalScriptWitness=i.inputs.finalScriptWitness.decode(n);break;case s.InputTypes.POR_COMMITMENT:c("input",n.key,s.InputTypes.POR_COMMITMENT),t.porCommitment=i.inputs.porCommitment.decode(n);break;case s.InputTypes.TAP_KEY_SIG:c("input",n.key,s.InputTypes.TAP_KEY_SIG),t.tapKeySig=i.inputs.tapKeySig.decode(n);break;case s.InputTypes.TAP_SCRIPT_SIG:void 0===t.tapScriptSig&&(t.tapScriptSig=[]),t.tapScriptSig.push(i.inputs.tapScriptSig.decode(n));break;case s.InputTypes.TAP_LEAF_SCRIPT:void 0===t.tapLeafScript&&(t.tapLeafScript=[]),t.tapLeafScript.push(i.inputs.tapLeafScript.decode(n));break;case s.InputTypes.TAP_BIP32_DERIVATION:void 0===t.tapBip32Derivation&&(t.tapBip32Derivation=[]),t.tapBip32Derivation.push(i.inputs.tapBip32Derivation.decode(n));break;case s.InputTypes.TAP_INTERNAL_KEY:c("input",n.key,s.InputTypes.TAP_INTERNAL_KEY),t.tapInternalKey=i.inputs.tapInternalKey.decode(n);break;case s.InputTypes.TAP_MERKLE_ROOT:c("input",n.key,s.InputTypes.TAP_MERKLE_ROOT),t.tapMerkleRoot=i.inputs.tapMerkleRoot.decode(n);break;default:t.unknownKeyVals||(t.unknownKeyVals=[]),t.unknownKeyVals.push(n)}f.push(t)}for(const e of o.range(d)){const t={};for(const r of n[e])switch(i.outputs.checkPubkey(r),r.key[0]){case s.OutputTypes.REDEEM_SCRIPT:if(c("output",r.key,s.OutputTypes.REDEEM_SCRIPT),void 0!==t.redeemScript)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");t.redeemScript=i.outputs.redeemScript.decode(r);break;case s.OutputTypes.WITNESS_SCRIPT:if(c("output",r.key,s.OutputTypes.WITNESS_SCRIPT),void 0!==t.witnessScript)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");t.witnessScript=i.outputs.witnessScript.decode(r);break;case s.OutputTypes.BIP32_DERIVATION:void 0===t.bip32Derivation&&(t.bip32Derivation=[]),t.bip32Derivation.push(i.outputs.bip32Derivation.decode(r));break;case s.OutputTypes.TAP_INTERNAL_KEY:c("output",r.key,s.OutputTypes.TAP_INTERNAL_KEY),t.tapInternalKey=i.outputs.tapInternalKey.decode(r);break;case s.OutputTypes.TAP_TREE:c("output",r.key,s.OutputTypes.TAP_TREE),t.tapTree=i.outputs.tapTree.decode(r);break;case s.OutputTypes.TAP_BIP32_DERIVATION:void 0===t.tapBip32Derivation&&(t.tapBip32Derivation=[]),t.tapBip32Derivation.push(i.outputs.tapBip32Derivation.decode(r));break;default:t.unknownKeyVals||(t.unknownKeyVals=[]),t.unknownKeyVals.push(r)}h.push(t)}return{globalMap:a,inputs:f,outputs:h}}t.psbtFromBuffer=function(e,t){let r=0;function n(){const t=a.decode(e,r);r+=a.encodingLength(t);const n=e.slice(r,r+t);return r+=t,n}function i(){return{key:n(),value:n()}}function c(){if(r>=e.length)throw new Error("Format Error: Unexpected End of PSBT");const t=0===e.readUInt8(r);return t&&r++,t}if(1886610036!==function(){const t=e.readUInt32BE(r);return r+=4,t}())throw new Error("Format Error: Invalid Magic Number");if(255!==function(){const t=e.readUInt8(r);return r+=1,t}())throw new Error("Format Error: Magic Number must be followed by 0xff separator");const l=[],d={};for(;!c();){const e=i(),t=e.key.toString("hex");if(d[t])throw new Error("Format Error: Keys must be unique for global keymap: key "+t);d[t]=1,l.push(e)}const f=l.filter((e=>e.key[0]===s.GlobalTypes.UNSIGNED_TX));if(1!==f.length)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const h=t(f[0].value),{inputCount:p,outputCount:g}=h.getInputOutputCounts(),m=[],y=[];for(const e of o.range(p)){const t={},r=[];for(;!c();){const n=i(),o=n.key.toString("hex");if(t[o])throw new Error("Format Error: Keys must be unique for each input: input index "+e+" key "+o);t[o]=1,r.push(n)}m.push(r)}for(const e of o.range(g)){const t={},r=[];for(;!c();){const n=i(),o=n.key.toString("hex");if(t[o])throw new Error("Format Error: Keys must be unique for each output: output index "+e+" key "+o);t[o]=1,r.push(n)}y.push(r)}return u(h,{globalMapKeyVals:l,inputKeyVals:m,outputKeyVals:y})},t.checkKeyBuffer=c,t.psbtFromKeyVals=u},36574:(e,t,r)=>{"use strict";function n(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),n(r(12974)),n(r(15312))},15312:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(71528),o=r(19254);t.psbtToBuffer=function({globalMap:e,inputs:t,outputs:r}){const{globalKeyVals:i,inputKeyVals:a,outputKeyVals:s}=c({globalMap:e,inputs:t,outputs:r}),u=o.keyValsToBuffer(i),l=e=>0===e.length?[n.from([0])]:e.map(o.keyValsToBuffer),d=l(a),f=l(s),h=n.allocUnsafe(5);return h.writeUIntBE(482972169471,0,5),n.concat([h,u].concat(d,f))};const a=(e,t)=>e.key.compare(t.key);function s(e,t){const r=new Set,n=Object.entries(e).reduce(((e,[n,i])=>{if("unknownKeyVals"===n)return e;const o=t[n];if(void 0===o)return e;const a=(Array.isArray(i)?i:[i]).map(o.encode);return a.map((e=>e.key.toString("hex"))).forEach((e=>{if(r.has(e))throw new Error("Serialize Error: Duplicate key: "+e);r.add(e)})),e.concat(a)}),[]),i=e.unknownKeyVals?e.unknownKeyVals.filter((e=>!r.has(e.key.toString("hex")))):[];return n.concat(i).sort(a)}function c({globalMap:e,inputs:t,outputs:r}){return{globalKeyVals:s(e,i.globals),inputKeyVals:t.map((e=>s(e,i.inputs))),outputKeyVals:r.map((e=>s(e,i.outputs)))}}t.psbtToKeyVals=c},95011:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(82190),o=r(36574),a=r(1847),s=r(96403);t.Psbt=class{constructor(e){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:e}}static fromBase64(e,t){const r=n.from(e,"base64");return this.fromBuffer(r,t)}static fromHex(e,t){const r=n.from(e,"hex");return this.fromBuffer(r,t)}static fromBuffer(e,t){const r=o.psbtFromBuffer(e,t),n=new this(r.globalMap.unsignedTx);return Object.assign(n,r),n}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return o.psbtToBuffer(this)}updateGlobal(e){return s.updateGlobal(e,this.globalMap),this}updateInput(e,t){const r=s.checkForInput(this.inputs,e);return s.updateInput(t,r),this}updateOutput(e,t){const r=s.checkForOutput(this.outputs,e);return s.updateOutput(t,r),this}addUnknownKeyValToGlobal(e){return s.checkHasKey(e,this.globalMap.unknownKeyVals,s.getEnumLength(a.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(e),this}addUnknownKeyValToInput(e,t){const r=s.checkForInput(this.inputs,e);return s.checkHasKey(t,r.unknownKeyVals,s.getEnumLength(a.InputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(t),this}addUnknownKeyValToOutput(e,t){const r=s.checkForOutput(this.outputs,e);return s.checkHasKey(t,r.unknownKeyVals,s.getEnumLength(a.OutputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(t),this}addInput(e){this.globalMap.unsignedTx.addInput(e),this.inputs.push({unknownKeyVals:[]});const t=e.unknownKeyVals||[],r=this.inputs.length-1;if(!Array.isArray(t))throw new Error("unknownKeyVals must be an Array");return t.forEach((e=>this.addUnknownKeyValToInput(r,e))),s.addInputAttributes(this.inputs,e),this}addOutput(e){this.globalMap.unsignedTx.addOutput(e),this.outputs.push({unknownKeyVals:[]});const t=e.unknownKeyVals||[],r=this.outputs.length-1;if(!Array.isArray(t))throw new Error("unknownKeyVals must be an Array");return t.forEach((e=>this.addUnknownKeyValToInput(r,e))),s.addOutputAttributes(this.outputs,e),this}clearFinalizedInput(e){const t=s.checkForInput(this.inputs,e);s.inputCheckUncleanFinalized(e,t);for(const e of Object.keys(t))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(e)||delete t[e];return this}combine(...e){const t=i.combine([this].concat(e));return Object.assign(this,t),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}}},1847:(e,t)=>{"use strict";var r,n,i;Object.defineProperty(t,"__esModule",{value:!0}),(i=t.GlobalTypes||(t.GlobalTypes={}))[i.UNSIGNED_TX=0]="UNSIGNED_TX",i[i.GLOBAL_XPUB=1]="GLOBAL_XPUB",t.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(n=t.InputTypes||(t.InputTypes={}))[n.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",n[n.WITNESS_UTXO=1]="WITNESS_UTXO",n[n.PARTIAL_SIG=2]="PARTIAL_SIG",n[n.SIGHASH_TYPE=3]="SIGHASH_TYPE",n[n.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",n[n.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",n[n.BIP32_DERIVATION=6]="BIP32_DERIVATION",n[n.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",n[n.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",n[n.POR_COMMITMENT=9]="POR_COMMITMENT",n[n.TAP_KEY_SIG=19]="TAP_KEY_SIG",n[n.TAP_SCRIPT_SIG=20]="TAP_SCRIPT_SIG",n[n.TAP_LEAF_SCRIPT=21]="TAP_LEAF_SCRIPT",n[n.TAP_BIP32_DERIVATION=22]="TAP_BIP32_DERIVATION",n[n.TAP_INTERNAL_KEY=23]="TAP_INTERNAL_KEY",n[n.TAP_MERKLE_ROOT=24]="TAP_MERKLE_ROOT",t.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment","tapKeySig","tapScriptSig","tapLeafScript","tapBip32Derivation","tapInternalKey","tapMerkleRoot"],(r=t.OutputTypes||(t.OutputTypes={}))[r.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",r[r.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",r[r.BIP32_DERIVATION=2]="BIP32_DERIVATION",r[r.TAP_INTERNAL_KEY=5]="TAP_INTERNAL_KEY",r[r.TAP_TREE=6]="TAP_TREE",r[r.TAP_BIP32_DERIVATION=7]="TAP_BIP32_DERIVATION",t.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation","tapInternalKey","tapTree","tapBip32Derivation"]},96403:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(71528);function o(e,t){const r=e[t];if(void 0===r)throw new Error(`No input #${t}`);return r}function a(e,t){const r=e[t];if(void 0===r)throw new Error(`No output #${t}`);return r}function s(e,t,r,n){throw new Error(`Data for ${e} key ${t} is incorrect: Expected ${r} and got ${JSON.stringify(n)}`)}function c(e){return(t,r)=>{for(const n of Object.keys(t)){const o=t[n],{canAdd:a,canAddToArray:c,check:u,expected:l}=i[e+"s"][n]||{};if(u)if(c){if(!Array.isArray(o)||r[n]&&!Array.isArray(r[n]))throw new Error(`Key type ${n} must be an array`);o.every(u)||s(e,n,l,o);const t=r[n]||[],i=new Set;if(!o.every((e=>c(t,e,i))))throw new Error("Can not add duplicate data to array");r[n]=t.concat(o)}else{if(u(o)||s(e,n,l,o),!a(r,o))throw new Error(`Can not add duplicate data to ${e}`);r[n]=o}}}}t.checkForInput=o,t.checkForOutput=a,t.checkHasKey=function(e,t,r){if(e.key[0]t.key.equals(e.key))).length)throw new Error(`Duplicate Key: ${e.key.toString("hex")}`)},t.getEnumLength=function(e){let t=0;return Object.keys(e).forEach((e=>{Number(isNaN(Number(e)))&&t++})),t},t.inputCheckUncleanFinalized=function(e,t){let r=!1;if(t.nonWitnessUtxo||t.witnessUtxo){const e=!!t.redeemScript,n=!!t.witnessScript,i=!e||!!t.finalScriptSig,o=!n||!!t.finalScriptWitness,a=!!t.finalScriptSig||!!t.finalScriptWitness;r=i&&o&&a}if(!1===r)throw new Error(`Input #${e} has too much or too little data to clean`)},t.updateGlobal=c("global"),t.updateInput=c("input"),t.updateOutput=c("output"),t.addInputAttributes=function(e,r){const n=o(e,e.length-1);t.updateInput(r,n)},t.addOutputAttributes=function(e,r){const n=a(e,e.length-1);t.updateOutput(r,n)},t.defaultVersionSetter=function(e,t){if(!n.isBuffer(t)||t.length<4)throw new Error("Set Version: Invalid Transaction");return t.writeUInt32LE(e,0),t},t.defaultLocktimeSetter=function(e,t){if(!n.isBuffer(t)||t.length<4)throw new Error("Set Locktime: Invalid Transaction");return t.writeUInt32LE(e,t.length-4),t}},30246:e=>{const t=2147483648;var r=function(e){if(!Array.isArray(e))throw new Error("Input must be an Array");if(0===e.length)throw new Error("Path must contain at least one level");for(var t=0;t=t)throw new Error("Invalid child index");if("h"===s[2]||"H"===s[2]||"'"===s[2])o[a]+=t;else if(0!=s[2].length)throw new Error("Invalid modifier")}return new r(o)},r.prototype.toPathArray=function(){return this.path},r.prototype.toString=function(e,r){for(var n=new Array(this.path.length),i=0;i"},e.exports=r},84090:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(56903),o=r(58334),a=r(95892),s=r(2401),c=r(37174),u=s.BufferN(32),l=s.compile({wif:s.UInt8,bip32:{public:s.UInt32,private:s.UInt32}}),d={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},f=2147483648,h=Math.pow(2,31)-1;function p(e){return s.String(e)&&null!==e.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}function g(e){return s.UInt32(e)&&e<=h}class m{constructor(e,t,r,n,i=0,o=0,a=0){this.__D=e,this.__Q=t,this.chainCode=r,this.network=n,this.__DEPTH=i,this.__INDEX=o,this.__PARENT_FINGERPRINT=a,s(l,n),this.lowR=!1}get depth(){return this.__DEPTH}get index(){return this.__INDEX}get parentFingerprint(){return this.__PARENT_FINGERPRINT}get publicKey(){return void 0===this.__Q&&(this.__Q=a.pointFromScalar(this.__D,!0)),this.__Q}get privateKey(){return this.__D}get identifier(){return i.hash160(this.publicKey)}get fingerprint(){return this.identifier.slice(0,4)}get compressed(){return!0}isNeutered(){return void 0===this.__D}neutered(){return v(this.publicKey,this.chainCode,this.network,this.depth,this.index,this.parentFingerprint)}toBase58(){const e=this.network,t=this.isNeutered()?e.bip32.public:e.bip32.private,r=n.allocUnsafe(78);return r.writeUInt32BE(t,0),r.writeUInt8(this.depth,4),r.writeUInt32BE(this.parentFingerprint,5),r.writeUInt32BE(this.index,9),this.chainCode.copy(r,13),this.isNeutered()?this.publicKey.copy(r,45):(r.writeUInt8(0,45),this.privateKey.copy(r,46)),o.encode(r)}toWIF(){if(!this.privateKey)throw new TypeError("Missing private key");return c.encode(this.network.wif,this.privateKey,!0)}derive(e){s(s.UInt32,e);const t=e>=f,r=n.allocUnsafe(37);if(t){if(this.isNeutered())throw new TypeError("Missing private key for hardened child key");r[0]=0,this.privateKey.copy(r,1),r.writeUInt32BE(e,33)}else this.publicKey.copy(r,0),r.writeUInt32BE(e,33);const o=i.hmacSHA512(this.chainCode,r),c=o.slice(0,32),u=o.slice(32);if(!a.isPrivate(c))return this.derive(e+1);let l;if(this.isNeutered()){const t=a.pointAddScalar(this.publicKey,c,!0);if(null===t)return this.derive(e+1);l=v(t,u,this.network,this.depth+1,e,this.fingerprint.readUInt32BE(0))}else{const t=a.privateAdd(this.privateKey,c);if(null==t)return this.derive(e+1);l=b(t,u,this.network,this.depth+1,e,this.fingerprint.readUInt32BE(0))}return l}deriveHardened(e){return s(g,e),this.derive(e+f)}derivePath(e){s(p,e);let t=e.split("/");if("m"===t[0]){if(this.parentFingerprint)throw new TypeError("Expected master, got child");t=t.slice(1)}return t.reduce(((e,t)=>{let r;return"'"===t.slice(-1)?(r=parseInt(t.slice(0,-1),10),e.deriveHardened(r)):(r=parseInt(t,10),e.derive(r))}),this)}sign(e,t){if(!this.privateKey)throw new Error("Missing private key");if(void 0===t&&(t=this.lowR),!1===t)return a.sign(e,this.privateKey);{let t=a.sign(e,this.privateKey);const r=n.alloc(32,0);let i=0;for(;t[0]>127;)i++,r.writeUIntLE(i,0,6),t=a.signWithEntropy(e,this.privateKey,r);return t}}verify(e,t){return a.verify(e,this.publicKey,t)}}function y(e,t,r){return b(e,t,r)}function b(e,t,r,n,i,o){if(s({privateKey:u,chainCode:u},{privateKey:e,chainCode:t}),r=r||d,!a.isPrivate(e))throw new TypeError("Private key not in range [1, n)");return new m(e,void 0,t,r,n,i,o)}function v(e,t,r,n,i,o){if(s({publicKey:s.BufferN(33),chainCode:u},{publicKey:e,chainCode:t}),r=r||d,!a.isPoint(e))throw new TypeError("Point is not on the curve");return new m(void 0,e,t,r,n,i,o)}t.fromBase58=function(e,t){const r=o.decode(e);if(78!==r.length)throw new TypeError("Invalid buffer length");t=t||d;const n=r.readUInt32BE(0);if(n!==t.bip32.private&&n!==t.bip32.public)throw new TypeError("Invalid network version");const i=r[4],a=r.readUInt32BE(5);if(0===i&&0!==a)throw new TypeError("Invalid parent fingerprint");const s=r.readUInt32BE(9);if(0===i&&0!==s)throw new TypeError("Invalid index");const c=r.slice(13,45);let u;if(n===t.bip32.private){if(0!==r.readUInt8(45))throw new TypeError("Invalid private key");u=b(r.slice(46,78),c,t,i,s,a)}else u=v(r.slice(45,78),c,t,i,s,a);return u},t.fromPrivateKey=y,t.fromPublicKey=function(e,t,r){return v(e,t,r)},t.fromSeed=function(e,t){if(s(s.Buffer,e),e.length<16)throw new TypeError("Seed should be at least 128 bits");if(e.length>64)throw new TypeError("Seed should be at most 512 bits");t=t||d;const r=i.hmacSHA512(n.from("Bitcoin seed","utf8"),e);return y(r.slice(0,32),r.slice(32),t)}},56903:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(23482),i=r(58355);t.hash160=function(e){const t=n("sha256").update(e).digest();try{return n("rmd160").update(t).digest()}catch(e){return n("ripemd160").update(t).digest()}},t.hmacSHA512=function(e,t){return i("sha512",e).update(t).digest()}},37786:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(84090);t.fromSeed=n.fromSeed,t.fromBase58=n.fromBase58,t.fromPublicKey=n.fromPublicKey,t.fromPrivateKey=n.fromPrivateKey},42314:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n={};let i;t.wordlists=n,t._default=i;try{t._default=i=r(Object(function(){var e=new Error("Cannot find module './wordlists/czech.json'");throw e.code="MODULE_NOT_FOUND",e}())),n.czech=i}catch(e){}try{t._default=i=r(Object(function(){var e=new Error("Cannot find module './wordlists/chinese_simplified.json'");throw e.code="MODULE_NOT_FOUND",e}())),n.chinese_simplified=i}catch(e){}try{t._default=i=r(Object(function(){var e=new Error("Cannot find module './wordlists/chinese_traditional.json'");throw e.code="MODULE_NOT_FOUND",e}())),n.chinese_traditional=i}catch(e){}try{t._default=i=r(Object(function(){var e=new Error("Cannot find module './wordlists/korean.json'");throw e.code="MODULE_NOT_FOUND",e}())),n.korean=i}catch(e){}try{t._default=i=r(Object(function(){var e=new Error("Cannot find module './wordlists/french.json'");throw e.code="MODULE_NOT_FOUND",e}())),n.french=i}catch(e){}try{t._default=i=r(Object(function(){var e=new Error("Cannot find module './wordlists/italian.json'");throw e.code="MODULE_NOT_FOUND",e}())),n.italian=i}catch(e){}try{t._default=i=r(Object(function(){var e=new Error("Cannot find module './wordlists/spanish.json'");throw e.code="MODULE_NOT_FOUND",e}())),n.spanish=i}catch(e){}try{t._default=i=r(Object(function(){var e=new Error("Cannot find module './wordlists/japanese.json'");throw e.code="MODULE_NOT_FOUND",e}())),n.japanese=i,n.JA=i}catch(e){}try{t._default=i=r(Object(function(){var e=new Error("Cannot find module './wordlists/portuguese.json'");throw e.code="MODULE_NOT_FOUND",e}())),n.portuguese=i}catch(e){}try{t._default=i=r(24573),n.english=i,n.EN=i}catch(e){}},2153:(e,t,r)=>{"use strict";var n=r(48764).Buffer;const i=r(23482),o=r(25632),a=r(61798);let s=r(42314)._default;const c="Invalid mnemonic",u="Invalid entropy",l="A wordlist is required but a default could not be found.\nPlease pass a 2048 word array explicitly.";function d(e){return(e||"").normalize("NFKD")}function f(e,t,r){for(;e.lengthf(e.toString(2),"0",8))).join("")}function g(e){const t=8*e.length/32,r=i("sha256").update(e).digest();return p(Array.from(r)).slice(0,t)}t.OI=function(e,t){return Promise.resolve().then((()=>function(e,t,r,n,i){return Promise.resolve().then((()=>new Promise(((r,n)=>{o.pbkdf2(e,t,2048,64,"sha512",((e,t)=>e?n(e):r(t)))}))))}(n.from(d(e),"utf8"),n.from(function(e){return"mnemonic"+(e||"")}(d(t)),"utf8"))))},t.OF=function(e,t,r){if((e=e||128)%32!=0)throw new TypeError(u);return function(e,t){if(n.isBuffer(e)||(e=n.from(e,"hex")),!(t=t||s))throw new Error(l);if(e.length<16)throw new TypeError(u);if(e.length>32)throw new TypeError(u);if(e.length%4!=0)throw new TypeError(u);const r=(p(Array.from(e))+g(e)).match(/(.{1,11})/g).map((e=>{const r=h(e);return t[r]}));return"あいこくしん"===t[0]?r.join(" "):r.join(" ")}((t=t||a)(e/8),r)},t._I=function(e,t){try{!function(e,t){if(!(t=t||s))throw new Error(l);const r=d(e).split(" ");if(r.length%3!=0)throw new Error(c);const i=r.map((e=>{const r=t.indexOf(e);if(-1===r)throw new Error(c);return f(r.toString(2),"0",11)})).join(""),o=32*Math.floor(i.length/33),a=i.slice(0,o),p=i.slice(o),m=a.match(/(.{1,8})/g).map(h);if(m.length<16)throw new Error(u);if(m.length>32)throw new Error(u);if(m.length%4!=0)throw new Error(u);const y=n.from(m);if(g(y)!==p)throw new Error("Invalid mnemonic checksum");y.toString("hex")}(e,t)}catch(e){return!1}return!0},r(42314).wordlists},93027:(e,t,r)=>{var n=r(89509).Buffer;e.exports={check:function(e){if(e.length<8)return!1;if(e.length>72)return!1;if(48!==e[0])return!1;if(e[1]!==e.length-2)return!1;if(2!==e[2])return!1;var t=e[3];if(0===t)return!1;if(5+t>=e.length)return!1;if(2!==e[4+t])return!1;var r=e[5+t];return!(0===r||6+t+r!==e.length||128&e[4]||t>1&&0===e[4]&&!(128&e[5])||128&e[t+6]||r>1&&0===e[t+6]&&!(128&e[t+7]))},decode:function(e){if(e.length<8)throw new Error("DER sequence length is too short");if(e.length>72)throw new Error("DER sequence length is too long");if(48!==e[0])throw new Error("Expected DER sequence");if(e[1]!==e.length-2)throw new Error("DER sequence length is invalid");if(2!==e[2])throw new Error("Expected DER integer");var t=e[3];if(0===t)throw new Error("R length is zero");if(5+t>=e.length)throw new Error("R length is too long");if(2!==e[4+t])throw new Error("Expected DER integer (2)");var r=e[5+t];if(0===r)throw new Error("S length is zero");if(6+t+r!==e.length)throw new Error("S length is invalid");if(128&e[4])throw new Error("R value is negative");if(t>1&&0===e[4]&&!(128&e[5]))throw new Error("R value excessively padded");if(128&e[t+6])throw new Error("S value is negative");if(r>1&&0===e[t+6]&&!(128&e[t+7]))throw new Error("S value excessively padded");return{r:e.slice(4,4+t),s:e.slice(6+t)}},encode:function(e,t){var r=e.length,i=t.length;if(0===r)throw new Error("R length is zero");if(0===i)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(i>33)throw new Error("S length is too long");if(128&e[0])throw new Error("R value is negative");if(128&t[0])throw new Error("S value is negative");if(r>1&&0===e[0]&&!(128&e[1]))throw new Error("R value excessively padded");if(i>1&&0===t[0]&&!(128&t[1]))throw new Error("S value excessively padded");var o=n.allocUnsafe(6+r+i);return o[0]=48,o[1]=o.length-2,o[2]=2,o[3]=e.length,e.copy(o,4),o[4+r]=2,o[5+r]=t.length,t.copy(o,6+r),o}}},42920:(e,t,r)=>{var n=r(39991),i={};for(var o in n)i[n[o]]=o;e.exports=i},72033:e=>{"use strict";for(var t="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r={},n=0;n>25;return(33554431&e)<<5^996825010&-(t>>0&1)^642813549&-(t>>1&1)^513874426&-(t>>2&1)^1027748829&-(t>>3&1)^705979059&-(t>>4&1)}function a(e){for(var t=1,r=0;r126)return"Invalid prefix ("+e+")";t=o(t)^n>>5}for(t=o(t),r=0;rt)return"Exceeds length limit";var n=e.toLowerCase(),i=e.toUpperCase();if(e!==n&&e!==i)return"Mixed-case string "+e;var s=(e=n).lastIndexOf("1");if(-1===s)return"No separator character for "+e;if(0===s)return"Missing prefix for "+e;var c=e.slice(0,s),u=e.slice(s+1);if(u.length<6)return"Data too short";var l=a(c);if("string"==typeof l)return l;for(var d=[],f=0;f=u.length||d.push(p)}return 1!==l?"Invalid checksum for "+e:{prefix:c,words:d}}function c(e,t,r,n){for(var i=0,o=0,a=(1<=r;)o-=r,s.push(i>>o&a);if(n)o>0&&s.push(i<=t)return"Excess padding";if(i<n)throw new TypeError("Exceeds length limit");var i=a(e=e.toLowerCase());if("string"==typeof i)throw new Error(i);for(var s=e+"1",c=0;c>5!=0)throw new Error("Non 5-bit word");i=o(i)^u,s+=t.charAt(u)}for(c=0;c<6;++c)i=o(i);for(i^=1,c=0;c<6;++c)s+=t.charAt(i>>5*(5-c)&31);return s},toWordsUnsafe:function(e){var t=c(e,8,5,!0);if(Array.isArray(t))return t},toWords:function(e){var t=c(e,8,5,!0);if(Array.isArray(t))return t;throw new Error(t)},fromWordsUnsafe:function(e){var t=c(e,5,8,!1);if(Array.isArray(t))return t},fromWords:function(e){var t=c(e,5,8,!1);if(Array.isArray(t))return t;throw new Error(t)}}},95488:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(74378),o=r(84972),a=r(73357),s=r(41838),c=r(72033),u=r(58334),l=r(2401);function d(e){const t=u.decode(e);if(t.length<21)throw new TypeError(e+" is too short");if(t.length>21)throw new TypeError(e+" is too long");return{version:t.readUInt8(0),hash:t.slice(1)}}function f(e){const t=c.decode(e),r=c.fromWords(t.words.slice(1));return{version:t.words[0],prefix:t.prefix,data:n.from(r)}}t.fromBase58Check=d,t.fromBech32=f,t.toBase58Check=function(e,t){l(s.tuple(s.Hash160bit,s.UInt8),arguments);const r=n.allocUnsafe(21);return r.writeUInt8(t,0),e.copy(r,1),u.encode(r)},t.toBech32=function(e,t,r){const n=c.toWords(e);return n.unshift(t),c.encode(r,n)},t.fromOutputScript=function(e,t){t=t||i.bitcoin;try{return o.p2pkh({output:e,network:t}).address}catch(e){}try{return o.p2sh({output:e,network:t}).address}catch(e){}try{return o.p2wpkh({output:e,network:t}).address}catch(e){}try{return o.p2wsh({output:e,network:t}).address}catch(e){}throw new Error(a.toASM(e)+" has no matching Address")},t.toOutputScript=function(e,t){let r,n;t=t||i.bitcoin;try{r=d(e)}catch(e){}if(r){if(r.version===t.pubKeyHash)return o.p2pkh({hash:r.hash}).output;if(r.version===t.scriptHash)return o.p2sh({hash:r.hash}).output}else{try{n=f(e)}catch(e){}if(n){if(n.prefix!==t.bech32)throw new Error(e+" has an invalid prefix");if(0===n.version){if(20===n.data.length)return o.p2wpkh({hash:n.data}).output;if(32===n.data.length)return o.p2wsh({hash:n.data}).output}}}throw new Error(e+" has no matching Script")}},87949:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(9357),o=r(5525),a=r(82737),s=r(41838),c=r(63673),u=r(2401),l=r(57795),d=new TypeError("Cannot compute merkle root for zero transactions"),f=new TypeError("Cannot compute witness commit for non-segwit block");class h{constructor(){this.version=1,this.prevHash=void 0,this.merkleRoot=void 0,this.timestamp=0,this.witnessCommit=void 0,this.bits=0,this.nonce=0,this.transactions=void 0}static fromBuffer(e){if(e.length<80)throw new Error("Buffer too small (< 80 bytes)");const t=new i.BufferReader(e),r=new h;if(r.version=t.readInt32(),r.prevHash=t.readSlice(32),r.merkleRoot=t.readSlice(32),r.timestamp=t.readUInt32(),r.bits=t.readUInt32(),r.nonce=t.readUInt32(),80===e.length)return r;const n=()=>{const e=a.Transaction.fromBuffer(t.buffer.slice(t.offset),!0);return t.offset+=e.byteLength(),e},o=t.readVarInt();r.transactions=[];for(let e=0;e>24)-3,r=8388607&e,i=n.alloc(32,0);return i.writeUIntBE(r,29-t,3),i}static calculateMerkleRoot(e,t){if(u([{getHash:s.Function}],e),0===e.length)throw d;if(t&&!p(e))throw f;const r=e.map((e=>e.getHash(t))),i=c(r,o.hash256);return t?o.hash256(n.concat([i,e[0].ins[0].witness[0]])):i}getWitnessCommit(){if(!p(this.transactions))return null;const e=this.transactions[0].outs.filter((e=>e.script.slice(0,6).equals(n.from("6a24aa21a9ed","hex")))).map((e=>e.script.slice(6,38)));if(0===e.length)return null;const t=e[e.length-1];return t instanceof n&&32===t.length?t:null}hasWitnessCommit(){return this.witnessCommit instanceof n&&32===this.witnessCommit.length||null!==this.getWitnessCommit()}hasWitness(){return(e=this.transactions)instanceof Array&&e.some((e=>"object"==typeof e&&e.ins instanceof Array&&e.ins.some((e=>"object"==typeof e&&e.witness instanceof Array&&e.witness.length>0))));var e}weight(){return 3*this.byteLength(!1,!1)+this.byteLength(!1,!0)}byteLength(e,t=!0){return e||!this.transactions?80:80+l.encodingLength(this.transactions.length)+this.transactions.reduce(((e,r)=>e+r.byteLength(t)),0)}getHash(){return o.hash256(this.toBuffer(!0))}getId(){return i.reverseBuffer(this.getHash()).toString("hex")}getUTCDate(){const e=new Date(0);return e.setUTCSeconds(this.timestamp),e}toBuffer(e){const t=n.allocUnsafe(this.byteLength(e)),r=new i.BufferWriter(t);return r.writeInt32(this.version),r.writeSlice(this.prevHash),r.writeSlice(this.merkleRoot),r.writeUInt32(this.timestamp),r.writeUInt32(this.bits),r.writeUInt32(this.nonce),e||!this.transactions||(l.encode(this.transactions.length,t,r.offset),r.offset+=l.encode.bytes,this.transactions.forEach((e=>{const n=e.byteLength();e.toBuffer(t,r.offset),r.offset+=n}))),t}toHex(e){return this.toBuffer(e).toString("hex")}checkTxRoots(){const e=this.hasWitnessCommit();return!(!e&&this.hasWitness())&&this.__checkMerkleRoot()&&(!e||this.__checkWitnessCommit())}checkProofOfWork(){const e=i.reverseBuffer(this.getHash()),t=h.calculateTarget(this.bits);return e.compare(t)<=0}__checkMerkleRoot(){if(!this.transactions)throw d;const e=h.calculateMerkleRoot(this.transactions);return 0===this.merkleRoot.compare(e)}__checkWitnessCommit(){if(!this.transactions)throw d;if(!this.hasWitnessCommit())throw f;const e=h.calculateMerkleRoot(this.transactions,!0);return 0===this.witnessCommit.compare(e)}}function p(e){return e instanceof Array&&e[0]&&e[0].ins&&e[0].ins instanceof Array&&e[0].ins[0]&&e[0].ins[0].witness&&e[0].ins[0].witness instanceof Array&&e[0].ins[0].witness.length>0}t.Block=h},9357:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(41838),o=r(2401),a=r(57795);function s(e,t){if("number"!=typeof e)throw new Error("cannot write a non-number as a number");if(e<0)throw new Error("specified a negative value for writing an unsigned value");if(e>t)throw new Error("RangeError: value out of range");if(Math.floor(e)!==e)throw new Error("value has a fractional component")}function c(e,t){const r=e.readUInt32LE(t);let n=e.readUInt32LE(t+4);return n*=4294967296,s(n+r,9007199254740991),n+r}function u(e,t,r){return s(t,9007199254740991),e.writeInt32LE(-1&t,r),e.writeUInt32LE(Math.floor(t/4294967296),r+4),r+8}t.readUInt64LE=c,t.writeUInt64LE=u,t.reverseBuffer=function(e){if(e.length<1)return e;let t=e.length-1,r=0;for(let n=0;nthis.writeVarSlice(e)))}},t.BufferReader=class{constructor(e,t=0){this.buffer=e,this.offset=t,o(i.tuple(i.Buffer,i.UInt32),[e,t])}readUInt8(){const e=this.buffer.readUInt8(this.offset);return this.offset++,e}readInt32(){const e=this.buffer.readInt32LE(this.offset);return this.offset+=4,e}readUInt32(){const e=this.buffer.readUInt32LE(this.offset);return this.offset+=4,e}readUInt64(){const e=c(this.buffer,this.offset);return this.offset+=8,e}readVarInt(){const e=a.decode(this.buffer,this.offset);return this.offset+=a.decode.bytes,e}readSlice(e){if(this.buffer.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(73357),i=r(18800),o=r(32334),a=r(7114),s=r(43645),c=r(16484),u=r(59920),l=r(78529),d=r(92476),f={P2MS:"multisig",NONSTANDARD:"nonstandard",NULLDATA:"nulldata",P2PK:"pubkey",P2PKH:"pubkeyhash",P2SH:"scripthash",P2WPKH:"witnesspubkeyhash",P2WSH:"witnessscripthash",WITNESS_COMMITMENT:"witnesscommitment"};t.types=f,t.output=function(e){if(l.output.check(e))return f.P2WPKH;if(d.output.check(e))return f.P2WSH;if(s.output.check(e))return f.P2PKH;if(c.output.check(e))return f.P2SH;const t=n.decompile(e);if(!t)throw new TypeError("Invalid script");return i.output.check(t)?f.P2MS:a.output.check(t)?f.P2PK:u.output.check(t)?f.WITNESS_COMMITMENT:o.output.check(t)?f.NULLDATA:f.NONSTANDARD},t.input=function(e,t){const r=n.decompile(e);if(!r)throw new TypeError("Invalid script");return s.input.check(r)?f.P2PKH:c.input.check(r,t)?f.P2SH:i.input.check(r,t)?f.P2MS:a.input.check(r)?f.P2PK:f.NONSTANDARD},t.witness=function(e,t){const r=n.decompile(e);if(!r)throw new TypeError("Invalid script");return l.input.check(r)?f.P2WPKH:d.input.check(r,t)?f.P2WSH:f.NONSTANDARD}},5525:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(23482);function i(e){try{return n("rmd160").update(e).digest()}catch(t){return n("ripemd160").update(e).digest()}}function o(e){return n("sha256").update(e).digest()}t.ripemd160=i,t.sha1=function(e){return n("sha1").update(e).digest()},t.sha256=o,t.hash160=function(e){return i(o(e))},t.hash256=function(e){return o(o(e))}},44018:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(74378),o=r(41838),a=r(95892),s=r(61798),c=r(2401),u=r(37174),l=c.maybe(c.compile({compressed:o.maybe(o.Boolean),network:o.maybe(o.Network)}));class d{constructor(e,t,r){this.__D=e,this.__Q=t,this.lowR=!1,void 0===r&&(r={}),this.compressed=void 0===r.compressed||r.compressed,this.network=r.network||i.bitcoin,void 0!==t&&(this.__Q=a.pointCompress(t,this.compressed))}get privateKey(){return this.__D}get publicKey(){return this.__Q||(this.__Q=a.pointFromScalar(this.__D,this.compressed)),this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return u.encode(this.network.wif,this.__D,this.compressed)}sign(e,t){if(!this.__D)throw new Error("Missing private key");if(void 0===t&&(t=this.lowR),!1===t)return a.sign(e,this.__D);{let t=a.sign(e,this.__D);const r=n.alloc(32,0);let i=0;for(;t[0]>127;)i++,r.writeUIntLE(i,0,6),t=a.signWithEntropy(e,this.__D,r);return t}}verify(e,t){return a.verify(e,this.publicKey,t)}}function f(e,t){if(c(o.Buffer256bit,e),!a.isPrivate(e))throw new TypeError("Private key not in range [1, n)");return c(l,t),new d(e,void 0,t)}t.fromPrivateKey=f,t.fromPublicKey=function(e,t){return c(a.isPoint,e),c(l,t),new d(void 0,e,t)},t.fromWIF=function(e,t){const r=u.decode(e),n=r.version;if(o.Array(t)){if(!(t=t.filter((e=>n===e.wif)).pop()))throw new Error("Unknown network version")}else if(t=t||i.bitcoin,n!==t.wif)throw new Error("Invalid network version");return f(r.privateKey,{compressed:r.compressed,network:t})},t.makeRandom=function(e){c(l,e),void 0===e&&(e={});const t=e.rng||s;let r;do{r=t(32),c(o.Buffer256bit,r)}while(!a.isPrivate(r));return f(r,e)}},17656:(e,t,r)=>{"use strict";r(37786),r(95488);const n=r(5525);t.eL=n,r(44018),r(74378),r(84972),r(73357),r(87949).Block,r(99930).Psbt,r(73357).OPS,r(82737).Transaction,r(31473).TransactionBuilder},74378:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bitcoin={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},t.regtest={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},t.testnet={messagePrefix:"Bitcoin Signed Message:\n",bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239}},36648:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(74378),i=r(73357),o=r(52691),a=r(2401),s=i.OPS;t.p2data=function(e,t){if(!e.data&&!e.output)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),a({network:a.maybe(a.Object),output:a.maybe(a.Buffer),data:a.maybe(a.arrayOf(a.Buffer))},e);const r={name:"embed",network:e.network||n.bitcoin};if(o.prop(r,"output",(()=>{if(e.data)return i.compile([s.OP_RETURN].concat(e.data))})),o.prop(r,"data",(()=>{if(e.output)return i.decompile(e.output).slice(1)})),t.validate&&e.output){const t=i.decompile(e.output);if(t[0]!==s.OP_RETURN)throw new TypeError("Output is invalid");if(!t.slice(1).every(a.Buffer))throw new TypeError("Output is invalid");if(e.data&&!function(e,t){return e.length===t.length&&e.every(((e,r)=>e.equals(t[r])))}(e.data,r.data))throw new TypeError("Data mismatch")}return Object.assign(r,e)}},84972:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(36648);t.embed=n.p2data;const i=r(98793);t.p2ms=i.p2ms;const o=r(97759);t.p2pk=o.p2pk;const a=r(44483);t.p2pkh=a.p2pkh;const s=r(21160);t.p2sh=s.p2sh;const c=r(18810);t.p2wpkh=c.p2wpkh;const u=r(82401);t.p2wsh=u.p2wsh},52691:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prop=function(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const e=r.call(this);return this[t]=e,e},set(e){Object.defineProperty(this,t,{configurable:!0,enumerable:!0,value:e,writable:!0})}})},t.value=function(e){let t;return()=>(void 0!==t||(t=e()),t)}},98793:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(74378),i=r(73357),o=r(52691),a=i.OPS,s=r(2401),c=r(95892),u=a.OP_RESERVED;function l(e,t){return e.length===t.length&&e.every(((e,r)=>e.equals(t[r])))}t.p2ms=function(e,t){if(!(e.input||e.output||e.pubkeys&&void 0!==e.m||e.signatures))throw new TypeError("Not enough data");function r(e){return i.isCanonicalScriptSignature(e)||void 0!==(t.allowIncomplete&&e===a.OP_0)}t=Object.assign({validate:!0},t||{}),s({network:s.maybe(s.Object),m:s.maybe(s.Number),n:s.maybe(s.Number),output:s.maybe(s.Buffer),pubkeys:s.maybe(s.arrayOf(c.isPoint)),signatures:s.maybe(s.arrayOf(r)),input:s.maybe(s.Buffer)},e);const d={network:e.network||n.bitcoin};let f=[],h=!1;function p(e){h||(h=!0,f=i.decompile(e),d.m=f[0]-u,d.n=f[f.length-2]-u,d.pubkeys=f.slice(1,-2))}if(o.prop(d,"output",(()=>{if(e.m&&d.n&&e.pubkeys)return i.compile([].concat(u+e.m,e.pubkeys,u+d.n,a.OP_CHECKMULTISIG))})),o.prop(d,"m",(()=>{if(d.output)return p(d.output),d.m})),o.prop(d,"n",(()=>{if(d.pubkeys)return d.pubkeys.length})),o.prop(d,"pubkeys",(()=>{if(e.output)return p(e.output),d.pubkeys})),o.prop(d,"signatures",(()=>{if(e.input)return i.decompile(e.input).slice(1)})),o.prop(d,"input",(()=>{if(e.signatures)return i.compile([a.OP_0].concat(e.signatures))})),o.prop(d,"witness",(()=>{if(d.input)return[]})),o.prop(d,"name",(()=>{if(d.m&&d.n)return`p2ms(${d.m} of ${d.n})`})),t.validate){if(e.output){if(p(e.output),!s.Number(f[0]))throw new TypeError("Output is invalid");if(!s.Number(f[f.length-2]))throw new TypeError("Output is invalid");if(f[f.length-1]!==a.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(d.m<=0||d.n>16||d.m>d.n||d.n!==f.length-3)throw new TypeError("Output is invalid");if(!d.pubkeys.every((e=>c.isPoint(e))))throw new TypeError("Output is invalid");if(void 0!==e.m&&e.m!==d.m)throw new TypeError("m mismatch");if(void 0!==e.n&&e.n!==d.n)throw new TypeError("n mismatch");if(e.pubkeys&&!l(e.pubkeys,d.pubkeys))throw new TypeError("Pubkeys mismatch")}if(e.pubkeys){if(void 0!==e.n&&e.n!==e.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(d.n=e.pubkeys.length,d.nd.m)throw new TypeError("Too many signatures provided")}if(e.input){if(e.input[0]!==a.OP_0)throw new TypeError("Input is invalid");if(0===d.signatures.length||!d.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(e.signatures&&!l(e.signatures,d.signatures))throw new TypeError("Signature mismatch");if(void 0!==e.m&&e.m!==e.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(d,e)}},97759:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(74378),i=r(73357),o=r(52691),a=r(2401),s=i.OPS,c=r(95892);t.p2pk=function(e,t){if(!(e.input||e.output||e.pubkey||e.input||e.signature))throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),a({network:a.maybe(a.Object),output:a.maybe(a.Buffer),pubkey:a.maybe(c.isPoint),signature:a.maybe(i.isCanonicalScriptSignature),input:a.maybe(a.Buffer)},e);const r=o.value((()=>i.decompile(e.input))),u={name:"p2pk",network:e.network||n.bitcoin};if(o.prop(u,"output",(()=>{if(e.pubkey)return i.compile([e.pubkey,s.OP_CHECKSIG])})),o.prop(u,"pubkey",(()=>{if(e.output)return e.output.slice(1,-1)})),o.prop(u,"signature",(()=>{if(e.input)return r()[0]})),o.prop(u,"input",(()=>{if(e.signature)return i.compile([e.signature])})),o.prop(u,"witness",(()=>{if(u.input)return[]})),t.validate){if(e.output){if(e.output[e.output.length-1]!==s.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!c.isPoint(u.pubkey))throw new TypeError("Output pubkey is invalid");if(e.pubkey&&!e.pubkey.equals(u.pubkey))throw new TypeError("Pubkey mismatch")}if(e.signature&&e.input&&!e.input.equals(u.input))throw new TypeError("Signature mismatch");if(e.input){if(1!==r().length)throw new TypeError("Input is invalid");if(!i.isCanonicalScriptSignature(u.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(u,e)}},44483:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(5525),o=r(74378),a=r(73357),s=r(52691),c=r(2401),u=a.OPS,l=r(95892),d=r(58334);t.p2pkh=function(e,t){if(!(e.address||e.hash||e.output||e.pubkey||e.input))throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),c({network:c.maybe(c.Object),address:c.maybe(c.String),hash:c.maybe(c.BufferN(20)),output:c.maybe(c.BufferN(25)),pubkey:c.maybe(l.isPoint),signature:c.maybe(a.isCanonicalScriptSignature),input:c.maybe(c.Buffer)},e);const r=s.value((()=>{const t=d.decode(e.address);return{version:t.readUInt8(0),hash:t.slice(1)}})),f=s.value((()=>a.decompile(e.input))),h=e.network||o.bitcoin,p={name:"p2pkh",network:h};if(s.prop(p,"address",(()=>{if(!p.hash)return;const e=n.allocUnsafe(21);return e.writeUInt8(h.pubKeyHash,0),p.hash.copy(e,1),d.encode(e)})),s.prop(p,"hash",(()=>e.output?e.output.slice(3,23):e.address?r().hash:e.pubkey||p.pubkey?i.hash160(e.pubkey||p.pubkey):void 0)),s.prop(p,"output",(()=>{if(p.hash)return a.compile([u.OP_DUP,u.OP_HASH160,p.hash,u.OP_EQUALVERIFY,u.OP_CHECKSIG])})),s.prop(p,"pubkey",(()=>{if(e.input)return f()[1]})),s.prop(p,"signature",(()=>{if(e.input)return f()[0]})),s.prop(p,"input",(()=>{if(e.pubkey&&e.signature)return a.compile([e.signature,e.pubkey])})),s.prop(p,"witness",(()=>{if(p.input)return[]})),t.validate){let t=n.from([]);if(e.address){if(r().version!==h.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(20!==r().hash.length)throw new TypeError("Invalid address");t=r().hash}if(e.hash){if(t.length>0&&!t.equals(e.hash))throw new TypeError("Hash mismatch");t=e.hash}if(e.output){if(25!==e.output.length||e.output[0]!==u.OP_DUP||e.output[1]!==u.OP_HASH160||20!==e.output[2]||e.output[23]!==u.OP_EQUALVERIFY||e.output[24]!==u.OP_CHECKSIG)throw new TypeError("Output is invalid");const r=e.output.slice(3,23);if(t.length>0&&!t.equals(r))throw new TypeError("Hash mismatch");t=r}if(e.pubkey){const r=i.hash160(e.pubkey);if(t.length>0&&!t.equals(r))throw new TypeError("Hash mismatch");t=r}if(e.input){const r=f();if(2!==r.length)throw new TypeError("Input is invalid");if(!a.isCanonicalScriptSignature(r[0]))throw new TypeError("Input has invalid signature");if(!l.isPoint(r[1]))throw new TypeError("Input has invalid pubkey");if(e.signature&&!e.signature.equals(r[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(r[1]))throw new TypeError("Pubkey mismatch");const n=i.hash160(r[1]);if(t.length>0&&!t.equals(n))throw new TypeError("Hash mismatch")}}return Object.assign(p,e)}},21160:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(5525),o=r(74378),a=r(73357),s=r(52691),c=r(2401),u=a.OPS,l=r(58334);t.p2sh=function(e,t){if(!(e.address||e.hash||e.output||e.redeem||e.input))throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),c({network:c.maybe(c.Object),address:c.maybe(c.String),hash:c.maybe(c.BufferN(20)),output:c.maybe(c.BufferN(23)),redeem:c.maybe({network:c.maybe(c.Object),output:c.maybe(c.Buffer),input:c.maybe(c.Buffer),witness:c.maybe(c.arrayOf(c.Buffer))}),input:c.maybe(c.Buffer),witness:c.maybe(c.arrayOf(c.Buffer))},e);let r=e.network;r||(r=e.redeem&&e.redeem.network||o.bitcoin);const d={network:r},f=s.value((()=>{const t=l.decode(e.address);return{version:t.readUInt8(0),hash:t.slice(1)}})),h=s.value((()=>a.decompile(e.input))),p=s.value((()=>{const t=h();return{network:r,output:t[t.length-1],input:a.compile(t.slice(0,-1)),witness:e.witness||[]}}));if(s.prop(d,"address",(()=>{if(!d.hash)return;const e=n.allocUnsafe(21);return e.writeUInt8(d.network.scriptHash,0),d.hash.copy(e,1),l.encode(e)})),s.prop(d,"hash",(()=>e.output?e.output.slice(2,22):e.address?f().hash:d.redeem&&d.redeem.output?i.hash160(d.redeem.output):void 0)),s.prop(d,"output",(()=>{if(d.hash)return a.compile([u.OP_HASH160,d.hash,u.OP_EQUAL])})),s.prop(d,"redeem",(()=>{if(e.input)return p()})),s.prop(d,"input",(()=>{if(e.redeem&&e.redeem.input&&e.redeem.output)return a.compile([].concat(a.decompile(e.redeem.input),e.redeem.output))})),s.prop(d,"witness",(()=>d.redeem&&d.redeem.witness?d.redeem.witness:d.input?[]:void 0)),s.prop(d,"name",(()=>{const e=["p2sh"];return void 0!==d.redeem&&e.push(d.redeem.name),e.join("-")})),t.validate){let t=n.from([]);if(e.address){if(f().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(20!==f().hash.length)throw new TypeError("Invalid address");t=f().hash}if(e.hash){if(t.length>0&&!t.equals(e.hash))throw new TypeError("Hash mismatch");t=e.hash}if(e.output){if(23!==e.output.length||e.output[0]!==u.OP_HASH160||20!==e.output[1]||e.output[22]!==u.OP_EQUAL)throw new TypeError("Output is invalid");const r=e.output.slice(2,22);if(t.length>0&&!t.equals(r))throw new TypeError("Hash mismatch");t=r}const o=e=>{if(e.output){const r=a.decompile(e.output);if(!r||r.length<1)throw new TypeError("Redeem.output too short");const n=i.hash160(e.output);if(t.length>0&&!t.equals(n))throw new TypeError("Hash mismatch");t=n}if(e.input){const t=e.input.length>0,r=e.witness&&e.witness.length>0;if(!t&&!r)throw new TypeError("Empty input");if(t&&r)throw new TypeError("Input and witness provided");if(t){const t=a.decompile(e.input);if(!a.isPushOnly(t))throw new TypeError("Non push-only scriptSig")}}};if(e.input){const e=h();if(!e||e.length<1)throw new TypeError("Input too short");if(!n.isBuffer(p().output))throw new TypeError("Input is invalid");o(p())}if(e.redeem){if(e.redeem.network&&e.redeem.network!==r)throw new TypeError("Network mismatch");if(e.input){const t=p();if(e.redeem.output&&!e.redeem.output.equals(t.output))throw new TypeError("Redeem.output mismatch");if(e.redeem.input&&!e.redeem.input.equals(t.input))throw new TypeError("Redeem.input mismatch")}o(e.redeem)}if(e.witness&&e.redeem&&e.redeem.witness&&!function(e,t){return e.length===t.length&&e.every(((e,r)=>e.equals(t[r])))}(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(d,e)}},18810:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(5525),o=r(74378),a=r(73357),s=r(52691),c=r(2401),u=a.OPS,l=r(95892),d=r(72033),f=n.alloc(0);t.p2wpkh=function(e,t){if(!(e.address||e.hash||e.output||e.pubkey||e.witness))throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),c({address:c.maybe(c.String),hash:c.maybe(c.BufferN(20)),input:c.maybe(c.BufferN(0)),network:c.maybe(c.Object),output:c.maybe(c.BufferN(22)),pubkey:c.maybe(l.isPoint),signature:c.maybe(a.isCanonicalScriptSignature),witness:c.maybe(c.arrayOf(c.Buffer))},e);const r=s.value((()=>{const t=d.decode(e.address),r=t.words.shift(),i=d.fromWords(t.words);return{version:r,prefix:t.prefix,data:n.from(i)}})),h=e.network||o.bitcoin,p={name:"p2wpkh",network:h};if(s.prop(p,"address",(()=>{if(!p.hash)return;const e=d.toWords(p.hash);return e.unshift(0),d.encode(h.bech32,e)})),s.prop(p,"hash",(()=>e.output?e.output.slice(2,22):e.address?r().data:e.pubkey||p.pubkey?i.hash160(e.pubkey||p.pubkey):void 0)),s.prop(p,"output",(()=>{if(p.hash)return a.compile([u.OP_0,p.hash])})),s.prop(p,"pubkey",(()=>e.pubkey?e.pubkey:e.witness?e.witness[1]:void 0)),s.prop(p,"signature",(()=>{if(e.witness)return e.witness[0]})),s.prop(p,"input",(()=>{if(p.witness)return f})),s.prop(p,"witness",(()=>{if(e.pubkey&&e.signature)return[e.signature,e.pubkey]})),t.validate){let t=n.from([]);if(e.address){if(h&&h.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(20!==r().data.length)throw new TypeError("Invalid address data");t=r().data}if(e.hash){if(t.length>0&&!t.equals(e.hash))throw new TypeError("Hash mismatch");t=e.hash}if(e.output){if(22!==e.output.length||e.output[0]!==u.OP_0||20!==e.output[1])throw new TypeError("Output is invalid");if(t.length>0&&!t.equals(e.output.slice(2)))throw new TypeError("Hash mismatch");t=e.output.slice(2)}if(e.pubkey){const r=i.hash160(e.pubkey);if(t.length>0&&!t.equals(r))throw new TypeError("Hash mismatch");if(t=r,!l.isPoint(e.pubkey)||33!==e.pubkey.length)throw new TypeError("Invalid pubkey for p2wpkh")}if(e.witness){if(2!==e.witness.length)throw new TypeError("Witness is invalid");if(!a.isCanonicalScriptSignature(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!l.isPoint(e.witness[1])||33!==e.witness[1].length)throw new TypeError("Witness has invalid pubkey");if(e.signature&&!e.signature.equals(e.witness[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(e.witness[1]))throw new TypeError("Pubkey mismatch");const r=i.hash160(e.witness[1]);if(t.length>0&&!t.equals(r))throw new TypeError("Hash mismatch")}}return Object.assign(p,e)}},82401:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(5525),o=r(74378),a=r(73357),s=r(52691),c=r(2401),u=a.OPS,l=r(95892),d=r(72033),f=n.alloc(0);function h(e){return!(!n.isBuffer(e)||65!==e.length||4!==e[0]||!l.isPoint(e))}t.p2wsh=function(e,t){if(!(e.address||e.hash||e.output||e.redeem||e.witness))throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),c({network:c.maybe(c.Object),address:c.maybe(c.String),hash:c.maybe(c.BufferN(32)),output:c.maybe(c.BufferN(34)),redeem:c.maybe({input:c.maybe(c.Buffer),network:c.maybe(c.Object),output:c.maybe(c.Buffer),witness:c.maybe(c.arrayOf(c.Buffer))}),input:c.maybe(c.BufferN(0)),witness:c.maybe(c.arrayOf(c.Buffer))},e);const r=s.value((()=>{const t=d.decode(e.address),r=t.words.shift(),i=d.fromWords(t.words);return{version:r,prefix:t.prefix,data:n.from(i)}})),l=s.value((()=>a.decompile(e.redeem.input)));let p=e.network;p||(p=e.redeem&&e.redeem.network||o.bitcoin);const g={network:p};if(s.prop(g,"address",(()=>{if(!g.hash)return;const e=d.toWords(g.hash);return e.unshift(0),d.encode(p.bech32,e)})),s.prop(g,"hash",(()=>e.output?e.output.slice(2):e.address?r().data:g.redeem&&g.redeem.output?i.sha256(g.redeem.output):void 0)),s.prop(g,"output",(()=>{if(g.hash)return a.compile([u.OP_0,g.hash])})),s.prop(g,"redeem",(()=>{if(e.witness)return{output:e.witness[e.witness.length-1],input:f,witness:e.witness.slice(0,-1)}})),s.prop(g,"input",(()=>{if(g.witness)return f})),s.prop(g,"witness",(()=>{if(e.redeem&&e.redeem.input&&e.redeem.input.length>0&&e.redeem.output&&e.redeem.output.length>0){const t=a.toStack(l());return g.redeem=Object.assign({witness:t},e.redeem),g.redeem.input=f,[].concat(t,e.redeem.output)}if(e.redeem&&e.redeem.output&&e.redeem.witness)return[].concat(e.redeem.witness,e.redeem.output)})),s.prop(g,"name",(()=>{const e=["p2wsh"];return void 0!==g.redeem&&e.push(g.redeem.name),e.join("-")})),t.validate){let t=n.from([]);if(e.address){if(r().prefix!==p.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(32!==r().data.length)throw new TypeError("Invalid address data");t=r().data}if(e.hash){if(t.length>0&&!t.equals(e.hash))throw new TypeError("Hash mismatch");t=e.hash}if(e.output){if(34!==e.output.length||e.output[0]!==u.OP_0||32!==e.output[1])throw new TypeError("Output is invalid");const r=e.output.slice(2);if(t.length>0&&!t.equals(r))throw new TypeError("Hash mismatch");t=r}if(e.redeem){if(e.redeem.network&&e.redeem.network!==p)throw new TypeError("Network mismatch");if(e.redeem.input&&e.redeem.input.length>0&&e.redeem.witness&&e.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(e.redeem.output){if(0===a.decompile(e.redeem.output).length)throw new TypeError("Redeem.output is invalid");const r=i.sha256(e.redeem.output);if(t.length>0&&!t.equals(r))throw new TypeError("Hash mismatch");t=r}if(e.redeem.input&&!a.isPushOnly(l()))throw new TypeError("Non push-only scriptSig");if(e.witness&&e.redeem.witness&&!function(e,t){return e.length===t.length&&e.every(((e,r)=>e.equals(t[r])))}(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&l().some(h)||e.redeem.output&&(a.decompile(e.redeem.output)||[]).some(h))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(e.witness&&e.witness.length>0){const t=e.witness[e.witness.length-1];if(e.redeem&&e.redeem.output&&!e.redeem.output.equals(t))throw new TypeError("Witness and redeem.output mismatch");if(e.witness.some(h)||(a.decompile(t)||[]).some(h))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(g,e)}},99930:(e,t,r)=>{"use strict";var n=r(48764).Buffer,i=r(25108);Object.defineProperty(t,"__esModule",{value:!0});const o=r(95011),a=r(3493),s=r(96403),c=r(95488),u=r(9357),l=r(5525),d=r(44018),f=r(74378),h=r(84972),p=r(73357),g=r(82737),m={network:f.bitcoin,maximumFeeRate:5e3};class y{constructor(e={},t=new o.Psbt(new v)){this.data=t,this.opts=Object.assign({},m,e),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},0===this.data.inputs.length&&this.setVersion(2);const r=(e,t,r,n)=>Object.defineProperty(e,t,{enumerable:r,writable:n});r(this,"__CACHE",!1,!0),r(this,"opts",!1,!0)}static fromBase64(e,t={}){const r=n.from(e,"base64");return this.fromBuffer(r,t)}static fromHex(e,t={}){const r=n.from(e,"hex");return this.fromBuffer(r,t)}static fromBuffer(e,t={}){const r=o.Psbt.fromBuffer(e,b),n=new y(t,r);var i,a;return i=n.__CACHE.__TX,a=n.__CACHE,i.ins.forEach((e=>{R(a,e)})),n}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(e){this.setVersion(e)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(e){this.setLocktime(e)}get txInputs(){return this.__CACHE.__TX.ins.map((e=>({hash:u.cloneBuffer(e.hash),index:e.index,sequence:e.sequence})))}get txOutputs(){return this.__CACHE.__TX.outs.map((e=>{let t;try{t=c.fromOutputScript(e.script,this.opts.network)}catch(e){}return{script:u.cloneBuffer(e.script),value:e.value,address:t}}))}combine(...e){return this.data.combine(...e.map((e=>e.data))),this}clone(){const e=y.fromBuffer(this.data.toBuffer());return e.opts=JSON.parse(JSON.stringify(this.opts)),e}setMaximumFeeRate(e){C(e),this.opts.maximumFeeRate=e}setVersion(e){C(e),N(this.data.inputs,"setVersion");const t=this.__CACHE;return t.__TX.version=e,t.__EXTRACTED_TX=void 0,this}setLocktime(e){C(e),N(this.data.inputs,"setLocktime");const t=this.__CACHE;return t.__TX.locktime=e,t.__EXTRACTED_TX=void 0,this}setInputSequence(e,t){C(t),N(this.data.inputs,"setInputSequence");const r=this.__CACHE;if(r.__TX.ins.length<=e)throw new Error("Input index too high");return r.__TX.ins[e].sequence=t,r.__EXTRACTED_TX=void 0,this}addInputs(e){return e.forEach((e=>this.addInput(e))),this}addInput(e){if(arguments.length>1||!e||void 0===e.hash||void 0===e.index)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");N(this.data.inputs,"addInput"),e.witnessScript&&Y(e.witnessScript);const t=this.__CACHE;this.data.addInput(e),R(t,t.__TX.ins[t.__TX.ins.length-1]);const r=this.data.inputs.length-1,n=this.data.inputs[r];return n.nonWitnessUtxo&&$(this.__CACHE,n,r),t.__FEE=void 0,t.__FEE_RATE=void 0,t.__EXTRACTED_TX=void 0,this}addOutputs(e){return e.forEach((e=>this.addOutput(e))),this}addOutput(e){if(arguments.length>1||!e||void 0===e.value||void 0===e.address&&void 0===e.script)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");N(this.data.inputs,"addOutput");const{address:t}=e;if("string"==typeof t){const{network:r}=this.opts,n=c.toOutputScript(t,r);e=Object.assign(e,{script:n})}const r=this.__CACHE;return this.data.addOutput(e),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}extractTransaction(e){if(!this.data.inputs.every(E))throw new Error("Not finalized");const t=this.__CACHE;if(e||function(e,t,r){const n=t.__FEE_RATE||e.getFeeRate(),i=t.__EXTRACTED_TX.virtualSize(),o=n*i;if(n>=r.maximumFeeRate)throw new Error(`Warning: You are paying around ${(o/1e8).toFixed(8)} in fees, which is ${n} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}(this,t,this.opts),t.__EXTRACTED_TX)return t.__EXTRACTED_TX;const r=t.__TX.clone();return K(this.data.inputs,r,t,!0),r}getFeeRate(){return U("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return U("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return s.checkForInput(this.data.inputs,0),Z(this.data.inputs.length).forEach((e=>this.finalizeInput(e))),this}finalizeInput(e,t=j){const r=s.checkForInput(this.data.inputs,e),{script:n,isP2SH:i,isP2WSH:o,isSegwit:a}=function(e,t,r){const n=r.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!t.redeemScript,i.isP2WSH=!!t.witnessScript,t.witnessScript)i.script=t.witnessScript;else if(t.redeemScript)i.script=t.redeemScript;else if(t.nonWitnessUtxo){const o=q(r,t,e),a=n.ins[e].index;i.script=o.outs[a].script}else t.witnessUtxo&&(i.script=t.witnessUtxo.script);return(t.witnessScript||x(i.script))&&(i.isSegwit=!0),i}(e,r,this.__CACHE);if(!n)throw new Error(`No script found for input #${e}`);!function(e){if(!e.sighashType||!e.partialSig)return;const{partialSig:t,sighashType:r}=e;t.forEach((e=>{const{hashType:t}=p.signature.decode(e.signature);if(r!==t)throw new Error("Signature sighash does not match input sighash type")}))}(r);const{finalScriptSig:c,finalScriptWitness:u}=t(e,r,n,a,i,o);if(c&&this.data.updateInput(e,{finalScriptSig:c}),u&&this.data.updateInput(e,{finalScriptWitness:u}),!c&&!u)throw new Error(`Unknown error finalizing input #${e}`);return this.data.clearFinalizedInput(e),this}getInputType(e){const t=s.checkForInput(this.data.inputs,e),r=X(z(e,t,this.__CACHE),e,"input",t.redeemScript||function(e){if(!e)return;const t=p.decompile(e);if(!t)return;const r=t[t.length-1];var i;if(n.isBuffer(r)&&!G(r)&&(i=r,!p.isCanonicalScriptSignature(i))&&p.decompile(r))return r}(t.finalScriptSig),t.witnessScript||function(e){if(!e)return;const t=V(e),r=t[t.length-1];return!G(r)&&p.decompile(r)?r:void 0}(t.finalScriptWitness));return("raw"===r.type?"":r.type+"-")+J(r.meaningfulScript)}inputHasPubkey(e,t){return function(e,t,r,n){const i=z(r,t,n),{meaningfulScript:o}=X(i,r,"input",t.redeemScript,t.witnessScript);return Q(e,o)}(t,s.checkForInput(this.data.inputs,e),e,this.__CACHE)}inputHasHDKey(e,t){const r=s.checkForInput(this.data.inputs,e),n=P(t);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}outputHasPubkey(e,t){return function(e,t,r,n){const i=n.__TX.outs[r].script,{meaningfulScript:o}=X(i,r,"output",t.redeemScript,t.witnessScript);return Q(e,o)}(t,s.checkForOutput(this.data.outputs,e),e,this.__CACHE)}outputHasHDKey(e,t){const r=s.checkForOutput(this.data.outputs,e),n=P(t);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}validateSignaturesOfAllInputs(){return s.checkForInput(this.data.inputs,0),Z(this.data.inputs.length).map((e=>this.validateSignaturesOfInput(e))).reduce(((e,t)=>!0===t&&e),!0)}validateSignaturesOfInput(e,t){const r=this.data.inputs[e],n=(r||{}).partialSig;if(!r||!n||n.length<1)throw new Error("No signatures to validate");const i=t?n.filter((e=>e.pubkey.equals(t))):n;if(i.length<1)throw new Error("No signatures for this pubkey");const o=[];let a,s,c;for(const t of i){const n=p.signature.decode(t.signature),{hash:i,script:u}=c!==n.hashType?H(e,Object.assign({},r,{sighashType:n.hashType}),this.__CACHE,!0):{hash:a,script:s};c=n.hashType,a=i,s=u,M(t.pubkey,u,"verify");const l=d.fromPublicKey(t.pubkey);o.push(l.verify(i,n.signature))}return o.every((e=>!0===e))}signAllInputsHD(e,t=[g.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey||!e.fingerprint)throw new Error("Need HDSigner to sign input");const r=[];for(const n of Z(this.data.inputs.length))try{this.signInputHD(n,e,t),r.push(!0)}catch(e){r.push(!1)}if(r.every((e=>!1===e)))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(e,t=[g.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!e||!e.publicKey||!e.fingerprint)return n(new Error("Need HDSigner to sign input"));const i=[],o=[];for(const r of Z(this.data.inputs.length))o.push(this.signInputHDAsync(r,e,t).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((e=>!1===e)))return n(new Error("No inputs were signed"));r()}))}))}signInputHD(e,t,r=[g.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");return W(e,this.data.inputs,t).forEach((t=>this.signInput(e,t,r))),this}signInputHDAsync(e,t,r=[g.Transaction.SIGHASH_ALL]){return new Promise(((n,i)=>{if(!t||!t.publicKey||!t.fingerprint)return i(new Error("Need HDSigner to sign input"));const o=W(e,this.data.inputs,t).map((t=>this.signInputAsync(e,t,r)));return Promise.all(o).then((()=>{n()})).catch(i)}))}signAllInputs(e,t=[g.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const r=[];for(const n of Z(this.data.inputs.length))try{this.signInput(n,e,t),r.push(!0)}catch(e){r.push(!1)}if(r.every((e=>!1===e)))throw new Error("No inputs were signed");return this}signAllInputsAsync(e,t=[g.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!e||!e.publicKey)return n(new Error("Need Signer to sign input"));const i=[],o=[];for(const[r]of this.data.inputs.entries())o.push(this.signInputAsync(r,e,t).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((e=>!1===e)))return n(new Error("No inputs were signed"));r()}))}))}signInput(e,t,r=[g.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=F(this.data.inputs,e,t.publicKey,this.__CACHE,r),o=[{pubkey:t.publicKey,signature:p.signature.encode(t.sign(n),i)}];return this.data.updateInput(e,{partialSig:o}),this}signInputAsync(e,t,r=[g.Transaction.SIGHASH_ALL]){return Promise.resolve().then((()=>{if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=F(this.data.inputs,e,t.publicKey,this.__CACHE,r);return Promise.resolve(t.sign(n)).then((r=>{const n=[{pubkey:t.publicKey,signature:p.signature.encode(r,i)}];this.data.updateInput(e,{partialSig:n})}))}))}toBuffer(){return w(this.__CACHE),this.data.toBuffer()}toHex(){return w(this.__CACHE),this.data.toHex()}toBase64(){return w(this.__CACHE),this.data.toBase64()}updateGlobal(e){return this.data.updateGlobal(e),this}updateInput(e,t){return t.witnessScript&&Y(t.witnessScript),this.data.updateInput(e,t),t.nonWitnessUtxo&&$(this.__CACHE,this.data.inputs[e],e),this}updateOutput(e,t){return this.data.updateOutput(e,t),this}addUnknownKeyValToGlobal(e){return this.data.addUnknownKeyValToGlobal(e),this}addUnknownKeyValToInput(e,t){return this.data.addUnknownKeyValToInput(e,t),this}addUnknownKeyValToOutput(e,t){return this.data.addUnknownKeyValToOutput(e,t),this}clearFinalizedInput(e){return this.data.clearFinalizedInput(e),this}}t.Psbt=y;const b=e=>new v(e);class v{constructor(e=n.from([2,0,0,0,0,0,0,0,0,0])){this.tx=g.Transaction.fromBuffer(e),function(e){if(!e.ins.every((e=>e.script&&0===e.script.length&&e.witness&&0===e.witness.length)))throw new Error("Format Error: Transaction ScriptSigs are not empty")}(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(e){if(void 0===e.hash||void 0===e.index||!n.isBuffer(e.hash)&&"string"!=typeof e.hash||"number"!=typeof e.index)throw new Error("Error adding input.");const t="string"==typeof e.hash?u.reverseBuffer(n.from(e.hash,"hex")):e.hash;this.tx.addInput(t,e.index,e.sequence)}addOutput(e){if(void 0===e.script||void 0===e.value||!n.isBuffer(e.script)||"number"!=typeof e.value)throw new Error("Error adding output.");this.tx.addOutput(e.script,e.value)}toBuffer(){return this.tx.toBuffer()}}function w(e){if(!1!==e.__UNSAFE_SIGN_NONSEGWIT)throw new Error("Not BIP174 compliant, can not export")}function _(e,t,r){if(!t)return!1;let n;if(n=r?r.map((e=>{const r=d.fromPublicKey(e,{compressed:!0}).publicKey;return t.find((e=>e.pubkey.equals(r)))})).filter((e=>!!e)):t,n.length>e)throw new Error("Too many signatures");return n.length===e}function E(e){return!!e.finalScriptSig||!!e.finalScriptWitness}function S(e){return t=>{try{return e({output:t}),!0}catch(e){return!1}}}const T=S(h.p2ms),A=S(h.p2pk),I=S(h.p2pkh),x=S(h.p2wpkh),O=S(h.p2wsh),k=S(h.p2sh);function P(e){return t=>!!t.masterFingerprint.equals(e.fingerprint)&&!!e.derivePath(t.path).publicKey.equals(t.pubkey)}function C(e){if("number"!=typeof e||e!==Math.floor(e)||e>4294967295||e<0)throw new Error("Invalid 32 bit integer")}function N(e,t){e.forEach((e=>{let r=!1,i=[];if(0===(e.partialSig||[]).length){if(!e.finalScriptSig&&!e.finalScriptWitness)return;i=function(e){const t=e.finalScriptSig&&p.decompile(e.finalScriptSig)||[],r=e.finalScriptWitness&&p.decompile(e.finalScriptWitness)||[];return t.concat(r).filter((e=>n.isBuffer(e)&&p.isCanonicalScriptSignature(e))).map((e=>({signature:e})))}(e)}else i=e.partialSig;if(i.forEach((e=>{const{hashType:n}=p.signature.decode(e.signature),i=[];switch(n&g.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput"),31&n){case g.Transaction.SIGHASH_ALL:break;case g.Transaction.SIGHASH_SINGLE:case g.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence")}-1===i.indexOf(t)&&(r=!0)})),r)throw new Error("Can not modify transaction, signatures exist.")}))}function M(e,t,r){if(!Q(e,t))throw new Error(`Can not ${r} for this input with the key ${e.toString("hex")}`)}function R(e,t){const r=u.reverseBuffer(n.from(t.hash)).toString("hex")+":"+t.index;if(e.__TX_IN_CACHE[r])throw new Error("Duplicate input detected.");e.__TX_IN_CACHE[r]=1}function D(e,t){return(r,n,i,o)=>{const a=e({redeem:{output:i}}).output;if(!n.equals(a))throw new Error(`${t} for ${o} #${r} doesn't match the scriptPubKey in the prevout`)}}const L=D(h.p2sh,"Redeem script"),B=D(h.p2wsh,"Witness script");function U(e,t,r,n){if(!r.every(E))throw new Error(`PSBT must be finalized to calculate ${t}`);if("__FEE_RATE"===e&&n.__FEE_RATE)return n.__FEE_RATE;if("__FEE"===e&&n.__FEE)return n.__FEE;let i,o=!0;return n.__EXTRACTED_TX?(i=n.__EXTRACTED_TX,o=!1):i=n.__TX.clone(),K(r,i,n,o),"__FEE_RATE"===e?n.__FEE_RATE:"__FEE"===e?n.__FEE:void 0}function j(e,t,r,i,o,s){const c=J(r);if(!function(e,t,r){switch(r){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return _(1,e.partialSig);case"multisig":const r=h.p2ms({output:t});return _(r.m,e.partialSig,r.pubkeys);default:return!1}}(t,r,c))throw new Error(`Can not finalize input #${e}`);return function(e,t,r,i,o,s){let c,u;const l=function(e,t,r){let n;switch(t){case"multisig":const t=function(e,t){return h.p2ms({output:e}).pubkeys.map((e=>(t.filter((t=>t.pubkey.equals(e)))[0]||{}).signature)).filter((e=>!!e))}(e,r);n=h.p2ms({output:e,signatures:t});break;case"pubkey":n=h.p2pk({output:e,signature:r[0].signature});break;case"pubkeyhash":n=h.p2pkh({output:e,pubkey:r[0].pubkey,signature:r[0].signature});break;case"witnesspubkeyhash":n=h.p2wpkh({output:e,pubkey:r[0].pubkey,signature:r[0].signature})}return n}(e,t,r),d=s?h.p2wsh({redeem:l}):null,f=o?h.p2sh({redeem:d||l}):null;return i?(u=function(e){let t=n.allocUnsafe(0);function r(e){const r=t.length,i=a.encodingLength(e);t=n.concat([t,n.allocUnsafe(i)]),a.encode(e,t,r)}function i(e){r(e.length),function(e){t=n.concat([t,n.from(e)])}(e)}var o;return r((o=e).length),o.forEach(i),t}(d?d.witness:l.witness),f&&(c=f.input)):c=f?f.input:l.input,{finalScriptSig:c,finalScriptWitness:u}}(r,c,t.partialSig,i,o,s)}function F(e,t,r,n,i){const o=s.checkForInput(e,t),{hash:a,sighashType:c,script:u}=H(t,o,n,!1,i);return M(r,u,"sign"),{hash:a,sighashType:c}}function H(e,t,r,n,o){const a=r.__TX,s=t.sighashType||g.Transaction.SIGHASH_ALL;if(o&&o.indexOf(s)<0){const e=function(e){let t=e&g.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(31&e){case g.Transaction.SIGHASH_ALL:t+="SIGHASH_ALL";break;case g.Transaction.SIGHASH_SINGLE:t+="SIGHASH_SINGLE";break;case g.Transaction.SIGHASH_NONE:t+="SIGHASH_NONE"}return t}(s);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${e}`)}let c,u;if(t.nonWitnessUtxo){const n=q(r,t,e),i=a.ins[e].hash,o=n.getHash();if(!i.equals(o))throw new Error(`Non-witness UTXO hash for input #${e} doesn't match the hash specified in the prevout`);const s=a.ins[e].index;u=n.outs[s]}else{if(!t.witnessUtxo)throw new Error("Need a Utxo input item for signing");u=t.witnessUtxo}const{meaningfulScript:l,type:d}=X(u.script,e,"input",t.redeemScript,t.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(d)>=0)c=a.hashForWitnessV0(e,l,u.value,s);else if(x(l)){const t=h.p2pkh({hash:l.slice(2)}).output;c=a.hashForWitnessV0(e,t,u.value,s)}else{if(void 0===t.nonWitnessUtxo&&!1===r.__UNSAFE_SIGN_NONSEGWIT)throw new Error(`Input #${e} has witnessUtxo but non-segwit script: ${l.toString("hex")}`);n||!1===r.__UNSAFE_SIGN_NONSEGWIT||i.warn("Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as the old TransactionBuilder class when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n*********************"),c=a.hashForSignature(e,l,s)}return{script:l,sighashType:s,hash:c}}function W(e,t,r){const n=s.checkForInput(t,e);if(!n.bip32Derivation||0===n.bip32Derivation.length)throw new Error("Need bip32Derivation to sign with HD");const i=n.bip32Derivation.map((e=>e.masterFingerprint.equals(r.fingerprint)?e:void 0)).filter((e=>!!e));if(0===i.length)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");return i.map((e=>{const t=r.derivePath(e.path);if(!e.pubkey.equals(t.publicKey))throw new Error("pubkey did not match bip32Derivation");return t}))}function V(e){let t=0;function r(){const r=a.decode(e,t);return t+=a.decode.bytes,r}return function(){const n=r(),i=[];for(let a=0;a{if(n&&e.finalScriptSig&&(t.ins[o].script=e.finalScriptSig),n&&e.finalScriptWitness&&(t.ins[o].witness=V(e.finalScriptWitness)),e.witnessUtxo)i+=e.witnessUtxo.value;else if(e.nonWitnessUtxo){const n=q(r,e,o),a=t.ins[o].index,s=n.outs[a];i+=s.value}}));const o=t.outs.reduce(((e,t)=>e+t.value),0),a=i-o;if(a<0)throw new Error("Outputs are spending more than Inputs");const s=t.virtualSize();r.__FEE=a,r.__EXTRACTED_TX=t,r.__FEE_RATE=Math.floor(a/s)}function q(e,t,r){const n=e.__NON_WITNESS_UTXO_TX_CACHE;return n[r]||$(e,t,r),n[r]}function z(e,t,r){if(void 0!==t.witnessUtxo)return t.witnessUtxo.script;if(void 0!==t.nonWitnessUtxo)return q(r,t,e).outs[r.__TX.ins[e].index].script;throw new Error("Can't find pubkey in input without Utxo data")}function G(e){return 33===e.length&&p.isCanonicalPubKey(e)}function X(e,t,r,n,i){const o=k(e),a=o&&n&&O(n),s=O(e);if(o&&void 0===n)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((s||a)&&void 0===i)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let c;return a?(c=i,L(t,e,n,r),B(t,n,i,r),Y(c)):s?(c=i,B(t,e,i,r),Y(c)):o?(c=n,L(t,e,n,r)):c=e,{meaningfulScript:c,type:a?"p2sh-p2wsh":o?"p2sh":s?"p2wsh":"raw"}}function Y(e){if(x(e)||k(e))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function Q(e,t){const r=l.hash160(e),n=p.decompile(t);if(null===n)throw new Error("Unknown script error");return n.some((t=>"number"!=typeof t&&(t.equals(e)||t.equals(r))))}function J(e){return x(e)?"witnesspubkeyhash":I(e)?"pubkeyhash":T(e)?"multisig":A(e)?"pubkey":"nonstandard"}function Z(e){return[...Array(e).keys()]}},73357:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(45815),o=r(24362),a=r(41838),s=r(93027),c=r(95892),u=r(13565),l=r(2401);t.OPS=r(39991);const d=r(42920),f=t.OPS.OP_RESERVED;function h(e){return a.Buffer(e)||function(e){return a.Number(e)&&(e===t.OPS.OP_0||e>=t.OPS.OP_1&&e<=t.OPS.OP_16||e===t.OPS.OP_1NEGATE)}(e)}function p(e){return a.Array(e)&&e.every(h)}function g(e){return 0===e.length?t.OPS.OP_0:1===e.length?e[0]>=1&&e[0]<=16?f+e[0]:129===e[0]?t.OPS.OP_1NEGATE:void 0:void 0}function m(e){return n.isBuffer(e)}function y(e){return n.isBuffer(e)}function b(e){if(m(e))return e;l(a.Array,e);const t=e.reduce(((e,t)=>y(t)?1===t.length&&void 0!==g(t)?e+1:e+u.encodingLength(t.length)+t.length:e+1),0),r=n.allocUnsafe(t);let i=0;if(e.forEach((e=>{if(y(e)){const t=g(e);if(void 0!==t)return r.writeUInt8(t,i),void(i+=1);i+=u.encode(r,e.length,i),e.copy(r,i),i+=e.length}else r.writeUInt8(e,i),i+=1})),i!==r.length)throw new Error("Could not decode chunks");return r}function v(e){if(r=e,a.Array(r))return e;var r;l(a.Buffer,e);const n=[];let i=0;for(;it.OPS.OP_0&&r<=t.OPS.OP_PUSHDATA4){const t=u.decode(e,i);if(null===t)return null;if(i+=t.size,i+t.number>e.length)return null;const r=e.slice(i,i+t.number);i+=t.number;const o=g(r);void 0!==o?n.push(o):n.push(r)}else n.push(r),i+=1}return n}function w(e){const t=-129&e;return t>0&&t<4}t.isPushOnly=p,t.compile=b,t.decompile=v,t.toASM=function(e){return m(e)&&(e=v(e)),e.map((e=>{if(y(e)){const t=g(e);if(void 0===t)return e.toString("hex");e=t}return d[e]})).join(" ")},t.fromASM=function(e){return l(a.String,e),b(e.split(" ").map((e=>void 0!==t.OPS[e]?t.OPS[e]:(l(a.Hex,e),n.from(e,"hex")))))},t.toStack=function(e){return e=v(e),l(p,e),e.map((e=>y(e)?e:e===t.OPS.OP_0?n.allocUnsafe(0):i.encode(e-f)))},t.isCanonicalPubKey=function(e){return c.isPoint(e)},t.isDefinedHashType=w,t.isCanonicalScriptSignature=function(e){return!!n.isBuffer(e)&&!!w(e[e.length-1])&&s.check(e.slice(0,-1))},t.number=i,t.signature=o},45815:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.decode=function(e,t,r){t=t||4,r=void 0===r||r;const n=e.length;if(0===n)return 0;if(n>t)throw new TypeError("Script number overflow");if(r&&0==(127&e[n-1])&&(n<=1||0==(128&e[n-2])))throw new Error("Non-minimally encoded script number");if(5===n){const t=e.readUInt32LE(0),r=e.readUInt8(4);return 128&r?-(4294967296*(-129&r)+t):4294967296*r+t}let i=0;for(let t=0;t2147483647?5:i>8388607?4:i>32767?3:i>127?2:i>0?1:0;var i;const o=n.allocUnsafe(r),a=e<0;for(let e=0;e>=8;return 128&o[r-1]?o.writeUInt8(a?128:0,r-1):a&&(o[r-1]|=128),o}},24362:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(41838),o=r(93027),a=r(2401),s=n.alloc(1,0);function c(e){let t=0;for(;0===e[t];)++t;return t===e.length?s:128&(e=e.slice(t))[0]?n.concat([s,e],1+e.length):e}function u(e){0===e[0]&&(e=e.slice(1));const t=n.alloc(32,0),r=Math.max(0,32-e.length);return e.copy(t,r),t}t.decode=function(e){const t=e.readUInt8(e.length-1),r=-129&t;if(r<=0||r>=4)throw new Error("Invalid hashType "+t);const i=o.decode(e.slice(0,-1)),a=u(i.r),s=u(i.s);return{signature:n.concat([a,s],64),hashType:t}},t.encode=function(e,t){a({signature:i.BufferN(64),hashType:i.UInt8},{signature:e,hashType:t});const r=-129&t;if(r<=0||r>=4)throw new Error("Invalid hashType "+t);const s=n.allocUnsafe(1);s.writeUInt8(t,0);const u=c(e.slice(0,32)),l=c(e.slice(32,64));return n.concat([o.encode(u,l),s])}},18800:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(28036);t.input=n;const i=r(35810);t.output=i},28036:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(73357),i=r(73357);function o(e){return e===i.OPS.OP_0||n.isCanonicalScriptSignature(e)}function a(e,t){const r=n.decompile(e);return!(r.length<2)&&r[0]===i.OPS.OP_0&&(t?r.slice(1).every(o):r.slice(1).every(n.isCanonicalScriptSignature))}t.check=a,a.toJSON=()=>"multisig input"},35810:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(73357),i=r(73357),o=r(41838),a=i.OPS.OP_RESERVED;function s(e,t){const r=n.decompile(e);if(r.length<4)return!1;if(r[r.length-1]!==i.OPS.OP_CHECKMULTISIG)return!1;if(!o.Number(r[0]))return!1;if(!o.Number(r[r.length-2]))return!1;const s=r[0]-a,c=r[r.length-2]-a;return!(s<=0)&&(!(c>16)&&(!(s>c)&&(c===r.length-3&&(!!t||r.slice(1,-2).every(n.isCanonicalPubKey)))))}t.check=s,s.toJSON=()=>"multi-sig output"},32334:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(73357),i=n.OPS;function o(e){const t=n.compile(e);return t.length>1&&t[0]===i.OP_RETURN}t.check=o,o.toJSON=()=>"null data output";const a={check:o};t.output=a},7114:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(98334);t.input=n;const i=r(93202);t.output=i},98334:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(73357);function i(e){const t=n.decompile(e);return 1===t.length&&n.isCanonicalScriptSignature(t[0])}t.check=i,i.toJSON=()=>"pubKey input"},93202:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(73357),i=r(73357);function o(e){const t=n.decompile(e);return 2===t.length&&n.isCanonicalPubKey(t[0])&&t[1]===i.OPS.OP_CHECKSIG}t.check=o,o.toJSON=()=>"pubKey output"},43645:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(93797);t.input=n;const i=r(41382);t.output=i},93797:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(73357);function i(e){const t=n.decompile(e);return 2===t.length&&n.isCanonicalScriptSignature(t[0])&&n.isCanonicalPubKey(t[1])}t.check=i,i.toJSON=()=>"pubKeyHash input"},41382:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(73357),i=r(73357);function o(e){const t=n.compile(e);return 25===t.length&&t[0]===i.OPS.OP_DUP&&t[1]===i.OPS.OP_HASH160&&20===t[2]&&t[23]===i.OPS.OP_EQUALVERIFY&&t[24]===i.OPS.OP_CHECKSIG}t.check=o,o.toJSON=()=>"pubKeyHash output"},16484:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(90904);t.input=n;const i=r(60897);t.output=i},90904:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(73357),o=r(18800),a=r(7114),s=r(43645),c=r(25876),u=r(15112);function l(e,t){const r=i.decompile(e);if(r.length<1)return!1;const l=r[r.length-1];if(!n.isBuffer(l))return!1;const d=i.decompile(i.compile(r.slice(0,-1))),f=i.decompile(l);return!!f&&!!i.isPushOnly(d)&&(1===r.length?u.check(f)||c.check(f):!(!s.input.check(d)||!s.output.check(f))||!(!o.input.check(d,t)||!o.output.check(f))||!(!a.input.check(d)||!a.output.check(f)))}t.check=l,l.toJSON=()=>"scriptHash input"},60897:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(73357),i=r(73357);function o(e){const t=n.compile(e);return 23===t.length&&t[0]===i.OPS.OP_HASH160&&20===t[1]&&t[22]===i.OPS.OP_EQUAL}t.check=o,o.toJSON=()=>"scriptHash output"},59920:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(55704);t.output=n},55704:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(73357),o=r(73357),a=r(41838),s=r(2401),c=n.from("aa21a9ed","hex");function u(e){const t=i.compile(e);return t.length>37&&t[0]===o.OPS.OP_RETURN&&36===t[1]&&t.slice(2,6).equals(c)}t.check=u,u.toJSON=()=>"Witness commitment output",t.encode=function(e){s(a.Hash256bit,e);const t=n.allocUnsafe(36);return c.copy(t,0),e.copy(t,4),i.compile([o.OPS.OP_RETURN,t])},t.decode=function(e){return s(u,e),i.decompile(e)[1].slice(4,36)}},78529:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(45764);t.input=n;const i=r(25876);t.output=i},45764:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(73357);function i(e){const t=n.decompile(e);return 2===t.length&&n.isCanonicalScriptSignature(t[0])&&(r=t[1],n.isCanonicalPubKey(r)&&33===r.length);var r}t.check=i,i.toJSON=()=>"witnessPubKeyHash input"},25876:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(73357),i=r(73357);function o(e){const t=n.compile(e);return 22===t.length&&t[0]===i.OPS.OP_0&&20===t[1]}t.check=o,o.toJSON=()=>"Witness pubKeyHash output"},92476:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(15114);t.input=n;const i=r(15112);t.output=i},15114:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(73357),o=r(2401),a=r(18800),s=r(7114),c=r(43645);function u(e,t){if(o(o.Array,e),e.length<1)return!1;const r=e[e.length-1];if(!n.isBuffer(r))return!1;const u=i.decompile(r);if(!u||0===u.length)return!1;const l=i.compile(e.slice(0,-1));return!(!c.input.check(l)||!c.output.check(u))||!(!a.input.check(l,t)||!a.output.check(u))||!(!s.input.check(l)||!s.output.check(u))}t.check=u,u.toJSON=()=>"witnessScriptHash input"},15112:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(73357),i=r(73357);function o(e){const t=n.compile(e);return 34===t.length&&t[0]===i.OPS.OP_0&&32===t[1]}t.check=o,o.toJSON=()=>"Witness scriptHash output"},82737:(e,t,r)=>{"use strict";var n=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const i=r(9357),o=r(5525),a=r(73357),s=r(73357),c=r(41838),u=r(2401),l=r(57795);function d(e){const t=e.length;return l.encodingLength(t)+t}const f=n.allocUnsafe(0),h=[],p=n.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),g=n.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),m=n.from("ffffffffffffffff","hex"),y={script:f,valueBuffer:m};class b{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(e,t){const r=new i.BufferReader(e),n=new b;n.version=r.readInt32();const o=r.readUInt8(),a=r.readUInt8();let s=!1;o===b.ADVANCED_TRANSACTION_MARKER&&a===b.ADVANCED_TRANSACTION_FLAG?s=!0:r.offset-=2;const c=r.readVarInt();for(let e=0;e0!==e.witness.length))}weight(){return 3*this.byteLength(!1)+this.byteLength(!0)}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(e=!0){const t=e&&this.hasWitnesses();return(t?10:8)+l.encodingLength(this.ins.length)+l.encodingLength(this.outs.length)+this.ins.reduce(((e,t)=>e+40+d(t.script)),0)+this.outs.reduce(((e,t)=>e+8+d(t.script)),0)+(t?this.ins.reduce(((e,t)=>e+function(e){const t=e.length;return l.encodingLength(t)+e.reduce(((e,t)=>e+d(t)),0)}(t.witness)),0):0)}clone(){const e=new b;return e.version=this.version,e.locktime=this.locktime,e.ins=this.ins.map((e=>({hash:e.hash,index:e.index,script:e.script,sequence:e.sequence,witness:e.witness}))),e.outs=this.outs.map((e=>({script:e.script,value:e.value}))),e}hashForSignature(e,t,r){if(u(c.tuple(c.UInt32,c.Buffer,c.Number),arguments),e>=this.ins.length)return g;const i=a.compile(a.decompile(t).filter((e=>e!==s.OPS.OP_CODESEPARATOR))),l=this.clone();if((31&r)===b.SIGHASH_NONE)l.outs=[],l.ins.forEach(((t,r)=>{r!==e&&(t.sequence=0)}));else if((31&r)===b.SIGHASH_SINGLE){if(e>=this.outs.length)return g;l.outs.length=e+1;for(let t=0;t{r!==e&&(t.sequence=0)}))}r&b.SIGHASH_ANYONECANPAY?(l.ins=[l.ins[e]],l.ins[0].script=i):(l.ins.forEach((e=>{e.script=f})),l.ins[e].script=i);const d=n.allocUnsafe(l.byteLength(!1)+4);return d.writeInt32LE(r,d.length-4),l.__toBuffer(d,0,!1),o.hash256(d)}hashForWitnessV0(e,t,r,a){u(c.tuple(c.UInt32,c.Buffer,c.Satoshi,c.UInt32),arguments);let s,l=n.from([]),f=p,h=p,g=p;if(a&b.SIGHASH_ANYONECANPAY||(l=n.allocUnsafe(36*this.ins.length),s=new i.BufferWriter(l,0),this.ins.forEach((e=>{s.writeSlice(e.hash),s.writeUInt32(e.index)})),h=o.hash256(l)),a&b.SIGHASH_ANYONECANPAY||(31&a)===b.SIGHASH_SINGLE||(31&a)===b.SIGHASH_NONE||(l=n.allocUnsafe(4*this.ins.length),s=new i.BufferWriter(l,0),this.ins.forEach((e=>{s.writeUInt32(e.sequence)})),g=o.hash256(l)),(31&a)!==b.SIGHASH_SINGLE&&(31&a)!==b.SIGHASH_NONE){const e=this.outs.reduce(((e,t)=>e+8+d(t.script)),0);l=n.allocUnsafe(e),s=new i.BufferWriter(l,0),this.outs.forEach((e=>{s.writeUInt64(e.value),s.writeVarSlice(e.script)})),f=o.hash256(l)}else if((31&a)===b.SIGHASH_SINGLE&&e{o.writeSlice(e.hash),o.writeUInt32(e.index),o.writeVarSlice(e.script),o.writeUInt32(e.sequence)})),o.writeVarInt(this.outs.length),this.outs.forEach((e=>{void 0!==e.value?o.writeUInt64(e.value):o.writeSlice(e.valueBuffer),o.writeVarSlice(e.script)})),a&&this.ins.forEach((e=>{o.writeVector(e.witness)})),o.writeUInt32(this.locktime),void 0!==t?e.slice(t,o.offset):e}}b.DEFAULT_SEQUENCE=4294967295,b.SIGHASH_ALL=1,b.SIGHASH_NONE=2,b.SIGHASH_SINGLE=3,b.SIGHASH_ANYONECANPAY=128,b.ADVANCED_TRANSACTION_MARKER=0,b.ADVANCED_TRANSACTION_FLAG=1,t.Transaction=b},31473:(e,t,r)=>{"use strict";var n=r(25108),i=r(48764).Buffer;Object.defineProperty(t,"__esModule",{value:!0});const o=r(95488),a=r(9357),s=r(47129),c=r(5525),u=r(44018),l=r(74378),d=r(84972),f=r(73357),h=r(73357),p=r(82737),g=r(41838),m=r(2401),y=s.types,b=new Set(["p2pkh","p2pk","p2wpkh","p2ms","p2sh-p2pkh","p2sh-p2pk","p2sh-p2wpkh","p2sh-p2ms","p2wsh-p2pkh","p2wsh-p2pk","p2wsh-p2ms","p2sh-p2wsh-p2pkh","p2sh-p2wsh-p2pk","p2sh-p2wsh-p2ms"]);function v(e,t,r){try{m(e,t)}catch(e){throw new Error(r)}}class w{constructor(e=l.bitcoin,t=2500){this.network=e,this.maximumFeeRate=t,this.__PREV_TX_SET={},this.__INPUTS=[],this.__TX=new p.Transaction,this.__TX.version=2,this.__USE_LOW_R=!1,n.warn("Deprecation Warning: TransactionBuilder will be removed in the future. (v6.x.x or later) Please use the Psbt class instead. Examples of usage are available in the transactions-psbt.js integration test file on our Github. A high level explanation is available in the psbt.ts and psbt.js files as well.")}static fromTransaction(e,t){const r=new w(t);return r.setVersion(e.version),r.setLockTime(e.locktime),e.outs.forEach((e=>{r.addOutput(e.script,e.value)})),e.ins.forEach((e=>{r.__addInputUnsafe(e.hash,e.index,{sequence:e.sequence,script:e.script,witness:e.witness})})),r.__INPUTS.forEach(((t,r)=>{!function(e,t,r){if(e.redeemScriptType!==y.P2MS||!e.redeemScript)return;if(e.pubkeys.length===e.signatures.length)return;const n=e.signatures.concat();e.signatures=e.pubkeys.map((i=>{const o=u.fromPublicKey(i);let a;return n.some(((i,s)=>{if(!i)return!1;const c=f.signature.decode(i),u=t.hashForSignature(r,e.redeemScript,c.hashType);return!!o.verify(u,c.signature)&&(n[s]=void 0,a=i,!0)})),a}))}(t,e,r)})),r}setLowR(e){return m(m.maybe(m.Boolean),e),void 0===e&&(e=!0),this.__USE_LOW_R=e,e}setLockTime(e){if(m(g.UInt32,e),this.__INPUTS.some((e=>!!e.signatures&&e.signatures.some((e=>void 0!==e)))))throw new Error("No, this would invalidate signatures");this.__TX.locktime=e}setVersion(e){m(g.UInt32,e),this.__TX.version=e}addInput(e,t,r,n){if(!this.__canModifyInputs())throw new Error("No, this would invalidate signatures");let o;if("string"==typeof(s=e)||s instanceof String)e=a.reverseBuffer(i.from(e,"hex"));else if(function(e){return e instanceof p.Transaction}(e)){const r=e.outs[t];n=r.script,o=r.value,e=e.getHash(!1)}var s;return this.__addInputUnsafe(e,t,{sequence:r,prevOutScript:n,value:o})}addOutput(e,t){if(!this.__canModifyOutputs())throw new Error("No, this would invalidate signatures");return"string"==typeof e&&(e=o.toOutputScript(e,this.network)),this.__TX.addOutput(e,t)}build(){return this.__build(!1)}buildIncomplete(){return this.__build(!0)}sign(e,t,r,i,o,a){!function({input:e,ourPubKey:t,keyPair:r,signatureHash:n,hashType:i,useLowR:o}){let a=!1;for(const[s,c]of e.pubkeys.entries()){if(!t.equals(c))continue;if(e.signatures[s])throw new Error("Signature already exists");if(33!==t.length&&e.hasWitness)throw new Error("BIP143 rejects uncompressed public keys in P2WPKH or P2WSH");const u=r.sign(n,o);e.signatures[s]=f.signature.encode(u,i),a=!0}if(!a)throw new Error("Key pair cannot sign for this input")}(function(e,t,r,i,o,a,s,c,u,l,h){let w;if("number"==typeof o)n.warn("DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface"),w=o;else{if("object"!=typeof o)throw new TypeError("TransactionBuilder sign first arg must be TxbSignArg or number");!function(e,t){if(!b.has(t.prevOutScriptType))throw new TypeError(`Unknown prevOutScriptType "${t.prevOutScriptType}"`);v(m.Number,t.vin,"sign must include vin parameter as Number (input index)"),v(g.Signer,t.keyPair,"sign must include keyPair parameter as Signer interface"),v(m.maybe(m.Number),t.hashType,"sign hashType parameter must be a number");const r=(e[t.vin]||[]).prevOutType,n=t.prevOutScriptType;switch(n){case"p2pkh":if(r&&"pubkeyhash"!==r)throw new TypeError(`input #${t.vin} is not of type p2pkh: ${r}`);v(m.value(void 0),t.witnessScript,`${n} requires NO witnessScript`),v(m.value(void 0),t.redeemScript,`${n} requires NO redeemScript`),v(m.value(void 0),t.witnessValue,`${n} requires NO witnessValue`);break;case"p2pk":if(r&&"pubkey"!==r)throw new TypeError(`input #${t.vin} is not of type p2pk: ${r}`);v(m.value(void 0),t.witnessScript,`${n} requires NO witnessScript`),v(m.value(void 0),t.redeemScript,`${n} requires NO redeemScript`),v(m.value(void 0),t.witnessValue,`${n} requires NO witnessValue`);break;case"p2wpkh":if(r&&"witnesspubkeyhash"!==r)throw new TypeError(`input #${t.vin} is not of type p2wpkh: ${r}`);v(m.value(void 0),t.witnessScript,`${n} requires NO witnessScript`),v(m.value(void 0),t.redeemScript,`${n} requires NO redeemScript`),v(g.Satoshi,t.witnessValue,`${n} requires witnessValue`);break;case"p2ms":if(r&&"multisig"!==r)throw new TypeError(`input #${t.vin} is not of type p2ms: ${r}`);v(m.value(void 0),t.witnessScript,`${n} requires NO witnessScript`),v(m.value(void 0),t.redeemScript,`${n} requires NO redeemScript`),v(m.value(void 0),t.witnessValue,`${n} requires NO witnessValue`);break;case"p2sh-p2wpkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${t.vin} is not of type p2sh-p2wpkh: ${r}`);v(m.value(void 0),t.witnessScript,`${n} requires NO witnessScript`),v(m.Buffer,t.redeemScript,`${n} requires redeemScript`),v(g.Satoshi,t.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2ms":case"p2sh-p2pk":case"p2sh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${t.vin} is not of type ${n}: ${r}`);v(m.value(void 0),t.witnessScript,`${n} requires NO witnessScript`),v(m.Buffer,t.redeemScript,`${n} requires redeemScript`),v(m.value(void 0),t.witnessValue,`${n} requires NO witnessValue`);break;case"p2wsh-p2ms":case"p2wsh-p2pk":case"p2wsh-p2pkh":if(r&&"witnessscripthash"!==r)throw new TypeError(`input #${t.vin} is not of type ${n}: ${r}`);v(m.Buffer,t.witnessScript,`${n} requires witnessScript`),v(m.value(void 0),t.redeemScript,`${n} requires NO redeemScript`),v(g.Satoshi,t.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2wsh-p2ms":case"p2sh-p2wsh-p2pk":case"p2sh-p2wsh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${t.vin} is not of type ${n}: ${r}`);v(m.Buffer,t.witnessScript,`${n} requires witnessScript`),v(m.Buffer,t.redeemScript,`${n} requires witnessScript`),v(g.Satoshi,t.witnessValue,`${n} requires witnessScript`)}}(t,o),({vin:w,keyPair:a,redeemScript:s,hashType:c,witnessValue:u,witnessScript:l}=o)}if(void 0===a)throw new Error("sign requires keypair");if(a.network&&a.network!==e)throw new TypeError("Inconsistent network");if(!t[w])throw new Error("No input at index: "+w);if(r(c=c||p.Transaction.SIGHASH_ALL))throw new Error("Transaction needs outputs");const _=t[w];if(void 0!==_.redeemScript&&s&&!_.redeemScript.equals(s))throw new Error("Inconsistent redeemScript");const S=a.publicKey||a.getPublicKey&&a.getPublicKey();if(!T(_)){if(void 0!==u){if(void 0!==_.value&&_.value!==u)throw new Error("Input did not match witnessValue");m(g.Satoshi,u),_.value=u}if(!T(_)){const e=function(e,t,r,n){if(r&&n){const i=d.p2wsh({redeem:{output:n}}),o=d.p2wsh({output:r}),a=d.p2sh({redeem:{output:r}}),s=d.p2sh({redeem:i});if(!i.hash.equals(o.hash))throw new Error("Witness script inconsistent with prevOutScript");if(!a.hash.equals(s.hash))throw new Error("Redeem script inconsistent with prevOutScript");const c=E(i.redeem.output,t);if(!c.pubkeys)throw new Error(c.type+" not supported as witnessScript ("+f.toASM(n)+")");e.signatures&&e.signatures.some((e=>void 0!==e))&&(c.signatures=e.signatures);const u=n;if(c.type===y.P2WPKH)throw new Error("P2SH(P2WSH(P2WPKH)) is a consensus failure");return{redeemScript:r,redeemScriptType:y.P2WSH,witnessScript:n,witnessScriptType:c.type,prevOutType:y.P2SH,prevOutScript:a.output,hasWitness:!0,signScript:u,signType:c.type,pubkeys:c.pubkeys,signatures:c.signatures,maxSignatures:c.maxSignatures}}if(r){const n=d.p2sh({redeem:{output:r}});if(e.prevOutScript){let t;try{t=d.p2sh({output:e.prevOutScript})}catch(e){throw new Error("PrevOutScript must be P2SH")}if(!n.hash.equals(t.hash))throw new Error("Redeem script inconsistent with prevOutScript")}const i=E(n.redeem.output,t);if(!i.pubkeys)throw new Error(i.type+" not supported as redeemScript ("+f.toASM(r)+")");e.signatures&&e.signatures.some((e=>void 0!==e))&&(i.signatures=e.signatures);let o=r;return i.type===y.P2WPKH&&(o=d.p2pkh({pubkey:i.pubkeys[0]}).output),{redeemScript:r,redeemScriptType:i.type,prevOutType:y.P2SH,prevOutScript:n.output,hasWitness:i.type===y.P2WPKH,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(n){const r=d.p2wsh({redeem:{output:n}});if(e.prevOutScript){const t=d.p2wsh({output:e.prevOutScript});if(!r.hash.equals(t.hash))throw new Error("Witness script inconsistent with prevOutScript")}const i=E(r.redeem.output,t);if(!i.pubkeys)throw new Error(i.type+" not supported as witnessScript ("+f.toASM(n)+")");e.signatures&&e.signatures.some((e=>void 0!==e))&&(i.signatures=e.signatures);const o=n;if(i.type===y.P2WPKH)throw new Error("P2WSH(P2WPKH) is a consensus failure");return{witnessScript:n,witnessScriptType:i.type,prevOutType:y.P2WSH,prevOutScript:r.output,hasWitness:!0,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(e.prevOutType&&e.prevOutScript){if(e.prevOutType===y.P2SH)throw new Error("PrevOutScript is "+e.prevOutType+", requires redeemScript");if(e.prevOutType===y.P2WSH)throw new Error("PrevOutScript is "+e.prevOutType+", requires witnessScript");if(!e.prevOutScript)throw new Error("PrevOutScript is missing");const r=E(e.prevOutScript,t);if(!r.pubkeys)throw new Error(r.type+" not supported ("+f.toASM(e.prevOutScript)+")");e.signatures&&e.signatures.some((e=>void 0!==e))&&(r.signatures=e.signatures);let n=e.prevOutScript;return r.type===y.P2WPKH&&(n=d.p2pkh({pubkey:r.pubkeys[0]}).output),{prevOutType:r.type,prevOutScript:e.prevOutScript,hasWitness:r.type===y.P2WPKH,signScript:n,signType:r.type,pubkeys:r.pubkeys,signatures:r.signatures,maxSignatures:r.maxSignatures}}const i=d.p2pkh({pubkey:t}).output;return{prevOutType:y.P2PKH,prevOutScript:i,hasWitness:!1,signScript:i,signType:y.P2PKH,pubkeys:[t],signatures:[void 0]}}(_,S,s,l);Object.assign(_,e)}if(!T(_))throw Error(_.prevOutType+" not supported")}let A;return A=_.hasWitness?i.hashForWitnessV0(w,_.signScript,_.value,c):i.hashForSignature(w,_.signScript,c),{input:_,ourPubKey:S,keyPair:a,signatureHash:A,hashType:c,useLowR:!!h}}(this.network,this.__INPUTS,this.__needsOutputs.bind(this),this.__TX,e,t,r,i,o,a,this.__USE_LOW_R))}__addInputUnsafe(e,t,r){if(p.Transaction.isCoinbaseHash(e))throw new Error("coinbase inputs not supported");const n=e.toString("hex")+":"+t;if(void 0!==this.__PREV_TX_SET[n])throw new Error("Duplicate TxOut: "+n);let i={};if(void 0!==r.script&&(i=_(r.script,r.witness||[])),void 0!==r.value&&(i.value=r.value),!i.prevOutScript&&r.prevOutScript){let e;if(!i.pubkeys&&!i.signatures){const t=E(r.prevOutScript);t.pubkeys&&(i.pubkeys=t.pubkeys,i.signatures=t.signatures),e=t.type}i.prevOutScript=r.prevOutScript,i.prevOutType=e||s.output(r.prevOutScript)}const o=this.__TX.addInput(e,t,r.sequence,r.scriptSig);return this.__INPUTS[o]=i,this.__PREV_TX_SET[n]=!0,o}__build(e){if(!e){if(!this.__TX.ins.length)throw new Error("Transaction has no inputs");if(!this.__TX.outs.length)throw new Error("Transaction has no outputs")}const t=this.__TX.clone();if(this.__INPUTS.forEach(((r,n)=>{if(!r.prevOutType&&!e)throw new Error("Transaction is not complete");const i=S(r.prevOutType,r,e);if(i)t.setInputScript(n,i.input),t.setWitness(n,i.witness);else{if(!e&&r.prevOutType===y.NONSTANDARD)throw new Error("Unknown input type");if(!e)throw new Error("Not enough information")}})),!e&&this.__overMaximumFees(t.virtualSize()))throw new Error("Transaction has absurd fees");return t}__canModifyInputs(){return this.__INPUTS.every((e=>!e.signatures||e.signatures.every((e=>!e||0!=(A(e)&p.Transaction.SIGHASH_ANYONECANPAY)))))}__needsOutputs(e){return e===p.Transaction.SIGHASH_ALL?0===this.__TX.outs.length:0===this.__TX.outs.length&&this.__INPUTS.some((e=>!!e.signatures&&e.signatures.some((e=>!!e&&!(A(e)&p.Transaction.SIGHASH_NONE)))))}__canModifyOutputs(){const e=this.__TX.ins.length,t=this.__TX.outs.length;return this.__INPUTS.every((r=>void 0===r.signatures||r.signatures.every((r=>{if(!r)return!0;const n=31&A(r);return n===p.Transaction.SIGHASH_NONE||n===p.Transaction.SIGHASH_SINGLE&&e<=t}))))}__overMaximumFees(e){return(this.__INPUTS.reduce(((e,t)=>e+(t.value>>>0)),0)-this.__TX.outs.reduce(((e,t)=>e+t.value),0))/e>this.maximumFeeRate}}function _(e,t,r,n){if(0===e.length&&0===t.length)return{};if(!r){let n=s.input(e,!0),i=s.witness(t,!0);n===y.NONSTANDARD&&(n=void 0),i===y.NONSTANDARD&&(i=void 0),r=n||i}switch(r){case y.P2WPKH:{const{output:e,pubkey:r,signature:n}=d.p2wpkh({witness:t});return{prevOutScript:e,prevOutType:y.P2WPKH,pubkeys:[r],signatures:[n]}}case y.P2PKH:{const{output:t,pubkey:r,signature:n}=d.p2pkh({input:e});return{prevOutScript:t,prevOutType:y.P2PKH,pubkeys:[r],signatures:[n]}}case y.P2PK:{const{signature:t}=d.p2pk({input:e});return{prevOutType:y.P2PK,pubkeys:[void 0],signatures:[t]}}case y.P2MS:{const{m:t,pubkeys:r,signatures:i}=d.p2ms({input:e,output:n},{allowIncomplete:!0});return{prevOutType:y.P2MS,pubkeys:r,signatures:i,maxSignatures:t}}}if(r===y.P2SH){const{output:r,redeem:n}=d.p2sh({input:e,witness:t}),i=s.output(n.output),o=_(n.input,n.witness,i,n.output);return o.prevOutType?{prevOutScript:r,prevOutType:y.P2SH,redeemScript:n.output,redeemScriptType:o.prevOutType,witnessScript:o.witnessScript,witnessScriptType:o.witnessScriptType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}if(r===y.P2WSH){const{output:r,redeem:n}=d.p2wsh({input:e,witness:t}),i=s.output(n.output);let o;return o=i===y.P2WPKH?_(n.input,n.witness,i):_(f.compile(n.witness),[],i,n.output),o.prevOutType?{prevOutScript:r,prevOutType:y.P2WSH,witnessScript:n.output,witnessScriptType:o.prevOutType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}return{prevOutType:y.NONSTANDARD,prevOutScript:e}}function E(e,t){m(g.Buffer,e);const r=s.output(e);switch(r){case y.P2PKH:{if(!t)return{type:r};const n=d.p2pkh({output:e}).hash,i=c.hash160(t);return n.equals(i)?{type:r,pubkeys:[t],signatures:[void 0]}:{type:r}}case y.P2WPKH:{if(!t)return{type:r};const n=d.p2wpkh({output:e}).hash,i=c.hash160(t);return n.equals(i)?{type:r,pubkeys:[t],signatures:[void 0]}:{type:r}}case y.P2PK:return{type:r,pubkeys:[d.p2pk({output:e}).pubkey],signatures:[void 0]};case y.P2MS:{const t=d.p2ms({output:e});return{type:r,pubkeys:t.pubkeys,signatures:t.pubkeys.map((()=>{})),maxSignatures:t.m}}}return{type:r}}function S(e,t,r){const n=t.pubkeys||[];let i=t.signatures||[];switch(e){case y.P2PKH:if(0===n.length)break;if(0===i.length)break;return d.p2pkh({pubkey:n[0],signature:i[0]});case y.P2WPKH:if(0===n.length)break;if(0===i.length)break;return d.p2wpkh({pubkey:n[0],signature:i[0]});case y.P2PK:if(0===n.length)break;if(0===i.length)break;return d.p2pk({signature:i[0]});case y.P2MS:{const e=t.maxSignatures;i=r?i.map((e=>e||h.OPS.OP_0)):i.filter((e=>e));const o=!r||e===i.length;return d.p2ms({m:e,pubkeys:n,signatures:i},{allowIncomplete:r,validate:o})}case y.P2SH:{const e=S(t.redeemScriptType,t,r);if(!e)return;return d.p2sh({redeem:{output:e.output||t.redeemScript,input:e.input,witness:e.witness}})}case y.P2WSH:{const e=S(t.witnessScriptType,t,r);if(!e)return;return d.p2wsh({redeem:{output:t.witnessScript,input:e.input,witness:e.witness}})}}}function T(e){return void 0!==e.signScript&&void 0!==e.signType&&void 0!==e.pubkeys&&void 0!==e.signatures&&e.signatures.length===e.pubkeys.length&&e.pubkeys.length>0&&(!1===e.hasWitness||void 0!==e.value)}function A(e){return e.readUInt8(e.length-1)}t.TransactionBuilder=w},41838:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(2401),i=Math.pow(2,31)-1;function o(e){return n.String(e)&&!!e.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}t.UInt31=function(e){return n.UInt32(e)&&e<=i},t.BIP32Path=o,o.toJSON=()=>"BIP32 derivation path",t.Signer=function(e){return(n.Buffer(e.publicKey)||"function"==typeof e.getPublicKey)&&"function"==typeof e.sign},t.Satoshi=function(e){return n.UInt53(e)&&e<=21e14},t.ECPoint=n.quacksLike("Point"),t.Network=n.compile({messagePrefix:n.oneOf(n.Buffer,n.String),bip32:{public:n.UInt32,private:n.UInt32},pubKeyHash:n.UInt8,scriptHash:n.UInt8,wif:n.UInt8}),t.Buffer256bit=n.BufferN(32),t.Hash160bit=n.BufferN(20),t.Hash256bit=n.BufferN(32),t.Number=n.Number,t.Array=n.Array,t.Boolean=n.Boolean,t.String=n.String,t.Buffer=n.Buffer,t.Hex=n.Hex,t.maybe=n.maybe,t.tuple=n.tuple,t.UInt8=n.UInt8,t.UInt32=n.UInt32,t.Function=n.Function,t.BufferN=n.BufferN,t.Null=n.Null,t.oneOf=n.oneOf},13550:function(e,t,r){!function(e,t){"use strict";function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function o(e,t,r){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var a;"object"==typeof e?e.exports=o:t.BN=o,o.BN=o,o.wordSize=26;try{a="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:r(46601).Buffer}catch(e){}function s(e,t){var r=e.charCodeAt(t);return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void n(!1,"Invalid character in "+e)}function c(e,t,r){var n=s(e,r);return r-1>=t&&(n|=s(e,r-1)<<4),n}function u(e,t,r,i){for(var o=0,a=0,s=Math.min(e.length,r),c=t;c=49?u-49+10:u>=17?u-17+10:u,n(u>=0&&a0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===r)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this._strip()},o.prototype._parseHex=function(e,t,r){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=2)i=c(e,t,n)<=18?(o-=18,a+=1,this.words[a]|=i>>>26):o+=8;else for(n=(e.length-t)%2==0?t+1:t;n=18?(o-=18,a+=1,this.words[a]|=i>>>26):o+=8;this._strip()},o.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,a=o%n,s=Math.min(o,o-a)+r,c=0,l=r;l1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{o.prototype[Symbol.for("nodejs.util.inspect.custom")]=d}catch(e){o.prototype.inspect=d}else o.prototype.inspect=d;function d(){return(this.red?""}var f=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],h=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],p=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function g(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,c=a/67108864|0;r.words[0]=s;for(var u=1;u>>26,d=67108863&c,f=Math.min(u,t.length-1),h=Math.max(0,u-e.length+1);h<=f;h++){var p=u-h|0;l+=(a=(i=0|e.words[p])*(o=0|t.words[h])+d)/67108864|0,d=67108863&a}r.words[u]=0|d,c=0|l}return 0!==c?r.words[u]=0|c:r.length--,r._strip()}o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,a=0;a>>24-i&16777215,(i+=2)>=26&&(i-=26,a--),r=0!==o||a!==this.length-1?f[6-c.length]+c+r:c+r}for(0!==o&&(r=o.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var u=h[e],l=p[e];r="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modrn(l).toString(e);r=(d=d.idivn(l)).isZero()?g+r:f[u-g.length]+g+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16,2)},a&&(o.prototype.toBuffer=function(e,t){return this.toArrayLike(a,e,t)}),o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,r){this._strip();var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0");var a=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,o);return this["_toArrayLike"+("le"===t?"LE":"BE")](a,i),a},o.prototype._toArrayLikeLE=function(e,t){for(var r=0,n=0,i=0,o=0;i>8&255),r>16&255),6===o?(r>24&255),n=0,o=0):(n=a>>>24,o+=2)}if(r=0&&(e[r--]=a>>8&255),r>=0&&(e[r--]=a>>16&255),6===o?(r>=0&&(e[r--]=a>>24&255),n=0,o=0):(n=a>>>24,o+=2)}if(r>=0)for(e[r--]=n;r>=0;)e[r--]=0},Math.clz32?o.prototype._countBits=function(e){return 32-Math.clz32(e)}:o.prototype._countBits=function(e){var t=e,r=0;return t>=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this._strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==o&&a>26,this.words[a]=67108863&t;if(0===o&&a>>13,h=0|a[1],p=8191&h,g=h>>>13,m=0|a[2],y=8191&m,b=m>>>13,v=0|a[3],w=8191&v,_=v>>>13,E=0|a[4],S=8191&E,T=E>>>13,A=0|a[5],I=8191&A,x=A>>>13,O=0|a[6],k=8191&O,P=O>>>13,C=0|a[7],N=8191&C,M=C>>>13,R=0|a[8],D=8191&R,L=R>>>13,B=0|a[9],U=8191&B,j=B>>>13,F=0|s[0],H=8191&F,W=F>>>13,V=0|s[1],$=8191&V,K=V>>>13,q=0|s[2],z=8191&q,G=q>>>13,X=0|s[3],Y=8191&X,Q=X>>>13,J=0|s[4],Z=8191&J,ee=J>>>13,te=0|s[5],re=8191&te,ne=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ce=8191&se,ue=se>>>13,le=0|s[8],de=8191&le,fe=le>>>13,he=0|s[9],pe=8191&he,ge=he>>>13;r.negative=e.negative^t.negative,r.length=19;var me=(u+(n=Math.imul(d,H))|0)+((8191&(i=(i=Math.imul(d,W))+Math.imul(f,H)|0))<<13)|0;u=((o=Math.imul(f,W))+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(p,H),i=(i=Math.imul(p,W))+Math.imul(g,H)|0,o=Math.imul(g,W);var ye=(u+(n=n+Math.imul(d,$)|0)|0)+((8191&(i=(i=i+Math.imul(d,K)|0)+Math.imul(f,$)|0))<<13)|0;u=((o=o+Math.imul(f,K)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(y,H),i=(i=Math.imul(y,W))+Math.imul(b,H)|0,o=Math.imul(b,W),n=n+Math.imul(p,$)|0,i=(i=i+Math.imul(p,K)|0)+Math.imul(g,$)|0,o=o+Math.imul(g,K)|0;var be=(u+(n=n+Math.imul(d,z)|0)|0)+((8191&(i=(i=i+Math.imul(d,G)|0)+Math.imul(f,z)|0))<<13)|0;u=((o=o+Math.imul(f,G)|0)+(i>>>13)|0)+(be>>>26)|0,be&=67108863,n=Math.imul(w,H),i=(i=Math.imul(w,W))+Math.imul(_,H)|0,o=Math.imul(_,W),n=n+Math.imul(y,$)|0,i=(i=i+Math.imul(y,K)|0)+Math.imul(b,$)|0,o=o+Math.imul(b,K)|0,n=n+Math.imul(p,z)|0,i=(i=i+Math.imul(p,G)|0)+Math.imul(g,z)|0,o=o+Math.imul(g,G)|0;var ve=(u+(n=n+Math.imul(d,Y)|0)|0)+((8191&(i=(i=i+Math.imul(d,Q)|0)+Math.imul(f,Y)|0))<<13)|0;u=((o=o+Math.imul(f,Q)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(S,H),i=(i=Math.imul(S,W))+Math.imul(T,H)|0,o=Math.imul(T,W),n=n+Math.imul(w,$)|0,i=(i=i+Math.imul(w,K)|0)+Math.imul(_,$)|0,o=o+Math.imul(_,K)|0,n=n+Math.imul(y,z)|0,i=(i=i+Math.imul(y,G)|0)+Math.imul(b,z)|0,o=o+Math.imul(b,G)|0,n=n+Math.imul(p,Y)|0,i=(i=i+Math.imul(p,Q)|0)+Math.imul(g,Y)|0,o=o+Math.imul(g,Q)|0;var we=(u+(n=n+Math.imul(d,Z)|0)|0)+((8191&(i=(i=i+Math.imul(d,ee)|0)+Math.imul(f,Z)|0))<<13)|0;u=((o=o+Math.imul(f,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(I,H),i=(i=Math.imul(I,W))+Math.imul(x,H)|0,o=Math.imul(x,W),n=n+Math.imul(S,$)|0,i=(i=i+Math.imul(S,K)|0)+Math.imul(T,$)|0,o=o+Math.imul(T,K)|0,n=n+Math.imul(w,z)|0,i=(i=i+Math.imul(w,G)|0)+Math.imul(_,z)|0,o=o+Math.imul(_,G)|0,n=n+Math.imul(y,Y)|0,i=(i=i+Math.imul(y,Q)|0)+Math.imul(b,Y)|0,o=o+Math.imul(b,Q)|0,n=n+Math.imul(p,Z)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(g,Z)|0,o=o+Math.imul(g,ee)|0;var _e=(u+(n=n+Math.imul(d,re)|0)|0)+((8191&(i=(i=i+Math.imul(d,ne)|0)+Math.imul(f,re)|0))<<13)|0;u=((o=o+Math.imul(f,ne)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(k,H),i=(i=Math.imul(k,W))+Math.imul(P,H)|0,o=Math.imul(P,W),n=n+Math.imul(I,$)|0,i=(i=i+Math.imul(I,K)|0)+Math.imul(x,$)|0,o=o+Math.imul(x,K)|0,n=n+Math.imul(S,z)|0,i=(i=i+Math.imul(S,G)|0)+Math.imul(T,z)|0,o=o+Math.imul(T,G)|0,n=n+Math.imul(w,Y)|0,i=(i=i+Math.imul(w,Q)|0)+Math.imul(_,Y)|0,o=o+Math.imul(_,Q)|0,n=n+Math.imul(y,Z)|0,i=(i=i+Math.imul(y,ee)|0)+Math.imul(b,Z)|0,o=o+Math.imul(b,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(g,re)|0,o=o+Math.imul(g,ne)|0;var Ee=(u+(n=n+Math.imul(d,oe)|0)|0)+((8191&(i=(i=i+Math.imul(d,ae)|0)+Math.imul(f,oe)|0))<<13)|0;u=((o=o+Math.imul(f,ae)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(N,H),i=(i=Math.imul(N,W))+Math.imul(M,H)|0,o=Math.imul(M,W),n=n+Math.imul(k,$)|0,i=(i=i+Math.imul(k,K)|0)+Math.imul(P,$)|0,o=o+Math.imul(P,K)|0,n=n+Math.imul(I,z)|0,i=(i=i+Math.imul(I,G)|0)+Math.imul(x,z)|0,o=o+Math.imul(x,G)|0,n=n+Math.imul(S,Y)|0,i=(i=i+Math.imul(S,Q)|0)+Math.imul(T,Y)|0,o=o+Math.imul(T,Q)|0,n=n+Math.imul(w,Z)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(_,Z)|0,o=o+Math.imul(_,ee)|0,n=n+Math.imul(y,re)|0,i=(i=i+Math.imul(y,ne)|0)+Math.imul(b,re)|0,o=o+Math.imul(b,ne)|0,n=n+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,ae)|0)+Math.imul(g,oe)|0,o=o+Math.imul(g,ae)|0;var Se=(u+(n=n+Math.imul(d,ce)|0)|0)+((8191&(i=(i=i+Math.imul(d,ue)|0)+Math.imul(f,ce)|0))<<13)|0;u=((o=o+Math.imul(f,ue)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(D,H),i=(i=Math.imul(D,W))+Math.imul(L,H)|0,o=Math.imul(L,W),n=n+Math.imul(N,$)|0,i=(i=i+Math.imul(N,K)|0)+Math.imul(M,$)|0,o=o+Math.imul(M,K)|0,n=n+Math.imul(k,z)|0,i=(i=i+Math.imul(k,G)|0)+Math.imul(P,z)|0,o=o+Math.imul(P,G)|0,n=n+Math.imul(I,Y)|0,i=(i=i+Math.imul(I,Q)|0)+Math.imul(x,Y)|0,o=o+Math.imul(x,Q)|0,n=n+Math.imul(S,Z)|0,i=(i=i+Math.imul(S,ee)|0)+Math.imul(T,Z)|0,o=o+Math.imul(T,ee)|0,n=n+Math.imul(w,re)|0,i=(i=i+Math.imul(w,ne)|0)+Math.imul(_,re)|0,o=o+Math.imul(_,ne)|0,n=n+Math.imul(y,oe)|0,i=(i=i+Math.imul(y,ae)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,ae)|0,n=n+Math.imul(p,ce)|0,i=(i=i+Math.imul(p,ue)|0)+Math.imul(g,ce)|0,o=o+Math.imul(g,ue)|0;var Te=(u+(n=n+Math.imul(d,de)|0)|0)+((8191&(i=(i=i+Math.imul(d,fe)|0)+Math.imul(f,de)|0))<<13)|0;u=((o=o+Math.imul(f,fe)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(U,H),i=(i=Math.imul(U,W))+Math.imul(j,H)|0,o=Math.imul(j,W),n=n+Math.imul(D,$)|0,i=(i=i+Math.imul(D,K)|0)+Math.imul(L,$)|0,o=o+Math.imul(L,K)|0,n=n+Math.imul(N,z)|0,i=(i=i+Math.imul(N,G)|0)+Math.imul(M,z)|0,o=o+Math.imul(M,G)|0,n=n+Math.imul(k,Y)|0,i=(i=i+Math.imul(k,Q)|0)+Math.imul(P,Y)|0,o=o+Math.imul(P,Q)|0,n=n+Math.imul(I,Z)|0,i=(i=i+Math.imul(I,ee)|0)+Math.imul(x,Z)|0,o=o+Math.imul(x,ee)|0,n=n+Math.imul(S,re)|0,i=(i=i+Math.imul(S,ne)|0)+Math.imul(T,re)|0,o=o+Math.imul(T,ne)|0,n=n+Math.imul(w,oe)|0,i=(i=i+Math.imul(w,ae)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,ae)|0,n=n+Math.imul(y,ce)|0,i=(i=i+Math.imul(y,ue)|0)+Math.imul(b,ce)|0,o=o+Math.imul(b,ue)|0,n=n+Math.imul(p,de)|0,i=(i=i+Math.imul(p,fe)|0)+Math.imul(g,de)|0,o=o+Math.imul(g,fe)|0;var Ae=(u+(n=n+Math.imul(d,pe)|0)|0)+((8191&(i=(i=i+Math.imul(d,ge)|0)+Math.imul(f,pe)|0))<<13)|0;u=((o=o+Math.imul(f,ge)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(U,$),i=(i=Math.imul(U,K))+Math.imul(j,$)|0,o=Math.imul(j,K),n=n+Math.imul(D,z)|0,i=(i=i+Math.imul(D,G)|0)+Math.imul(L,z)|0,o=o+Math.imul(L,G)|0,n=n+Math.imul(N,Y)|0,i=(i=i+Math.imul(N,Q)|0)+Math.imul(M,Y)|0,o=o+Math.imul(M,Q)|0,n=n+Math.imul(k,Z)|0,i=(i=i+Math.imul(k,ee)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,ee)|0,n=n+Math.imul(I,re)|0,i=(i=i+Math.imul(I,ne)|0)+Math.imul(x,re)|0,o=o+Math.imul(x,ne)|0,n=n+Math.imul(S,oe)|0,i=(i=i+Math.imul(S,ae)|0)+Math.imul(T,oe)|0,o=o+Math.imul(T,ae)|0,n=n+Math.imul(w,ce)|0,i=(i=i+Math.imul(w,ue)|0)+Math.imul(_,ce)|0,o=o+Math.imul(_,ue)|0,n=n+Math.imul(y,de)|0,i=(i=i+Math.imul(y,fe)|0)+Math.imul(b,de)|0,o=o+Math.imul(b,fe)|0;var Ie=(u+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,ge)|0)+Math.imul(g,pe)|0))<<13)|0;u=((o=o+Math.imul(g,ge)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(U,z),i=(i=Math.imul(U,G))+Math.imul(j,z)|0,o=Math.imul(j,G),n=n+Math.imul(D,Y)|0,i=(i=i+Math.imul(D,Q)|0)+Math.imul(L,Y)|0,o=o+Math.imul(L,Q)|0,n=n+Math.imul(N,Z)|0,i=(i=i+Math.imul(N,ee)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(k,re)|0,i=(i=i+Math.imul(k,ne)|0)+Math.imul(P,re)|0,o=o+Math.imul(P,ne)|0,n=n+Math.imul(I,oe)|0,i=(i=i+Math.imul(I,ae)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,ae)|0,n=n+Math.imul(S,ce)|0,i=(i=i+Math.imul(S,ue)|0)+Math.imul(T,ce)|0,o=o+Math.imul(T,ue)|0,n=n+Math.imul(w,de)|0,i=(i=i+Math.imul(w,fe)|0)+Math.imul(_,de)|0,o=o+Math.imul(_,fe)|0;var xe=(u+(n=n+Math.imul(y,pe)|0)|0)+((8191&(i=(i=i+Math.imul(y,ge)|0)+Math.imul(b,pe)|0))<<13)|0;u=((o=o+Math.imul(b,ge)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(U,Y),i=(i=Math.imul(U,Q))+Math.imul(j,Y)|0,o=Math.imul(j,Q),n=n+Math.imul(D,Z)|0,i=(i=i+Math.imul(D,ee)|0)+Math.imul(L,Z)|0,o=o+Math.imul(L,ee)|0,n=n+Math.imul(N,re)|0,i=(i=i+Math.imul(N,ne)|0)+Math.imul(M,re)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(k,oe)|0,i=(i=i+Math.imul(k,ae)|0)+Math.imul(P,oe)|0,o=o+Math.imul(P,ae)|0,n=n+Math.imul(I,ce)|0,i=(i=i+Math.imul(I,ue)|0)+Math.imul(x,ce)|0,o=o+Math.imul(x,ue)|0,n=n+Math.imul(S,de)|0,i=(i=i+Math.imul(S,fe)|0)+Math.imul(T,de)|0,o=o+Math.imul(T,fe)|0;var Oe=(u+(n=n+Math.imul(w,pe)|0)|0)+((8191&(i=(i=i+Math.imul(w,ge)|0)+Math.imul(_,pe)|0))<<13)|0;u=((o=o+Math.imul(_,ge)|0)+(i>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,n=Math.imul(U,Z),i=(i=Math.imul(U,ee))+Math.imul(j,Z)|0,o=Math.imul(j,ee),n=n+Math.imul(D,re)|0,i=(i=i+Math.imul(D,ne)|0)+Math.imul(L,re)|0,o=o+Math.imul(L,ne)|0,n=n+Math.imul(N,oe)|0,i=(i=i+Math.imul(N,ae)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,ae)|0,n=n+Math.imul(k,ce)|0,i=(i=i+Math.imul(k,ue)|0)+Math.imul(P,ce)|0,o=o+Math.imul(P,ue)|0,n=n+Math.imul(I,de)|0,i=(i=i+Math.imul(I,fe)|0)+Math.imul(x,de)|0,o=o+Math.imul(x,fe)|0;var ke=(u+(n=n+Math.imul(S,pe)|0)|0)+((8191&(i=(i=i+Math.imul(S,ge)|0)+Math.imul(T,pe)|0))<<13)|0;u=((o=o+Math.imul(T,ge)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(U,re),i=(i=Math.imul(U,ne))+Math.imul(j,re)|0,o=Math.imul(j,ne),n=n+Math.imul(D,oe)|0,i=(i=i+Math.imul(D,ae)|0)+Math.imul(L,oe)|0,o=o+Math.imul(L,ae)|0,n=n+Math.imul(N,ce)|0,i=(i=i+Math.imul(N,ue)|0)+Math.imul(M,ce)|0,o=o+Math.imul(M,ue)|0,n=n+Math.imul(k,de)|0,i=(i=i+Math.imul(k,fe)|0)+Math.imul(P,de)|0,o=o+Math.imul(P,fe)|0;var Pe=(u+(n=n+Math.imul(I,pe)|0)|0)+((8191&(i=(i=i+Math.imul(I,ge)|0)+Math.imul(x,pe)|0))<<13)|0;u=((o=o+Math.imul(x,ge)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,n=Math.imul(U,oe),i=(i=Math.imul(U,ae))+Math.imul(j,oe)|0,o=Math.imul(j,ae),n=n+Math.imul(D,ce)|0,i=(i=i+Math.imul(D,ue)|0)+Math.imul(L,ce)|0,o=o+Math.imul(L,ue)|0,n=n+Math.imul(N,de)|0,i=(i=i+Math.imul(N,fe)|0)+Math.imul(M,de)|0,o=o+Math.imul(M,fe)|0;var Ce=(u+(n=n+Math.imul(k,pe)|0)|0)+((8191&(i=(i=i+Math.imul(k,ge)|0)+Math.imul(P,pe)|0))<<13)|0;u=((o=o+Math.imul(P,ge)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,n=Math.imul(U,ce),i=(i=Math.imul(U,ue))+Math.imul(j,ce)|0,o=Math.imul(j,ue),n=n+Math.imul(D,de)|0,i=(i=i+Math.imul(D,fe)|0)+Math.imul(L,de)|0,o=o+Math.imul(L,fe)|0;var Ne=(u+(n=n+Math.imul(N,pe)|0)|0)+((8191&(i=(i=i+Math.imul(N,ge)|0)+Math.imul(M,pe)|0))<<13)|0;u=((o=o+Math.imul(M,ge)|0)+(i>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,n=Math.imul(U,de),i=(i=Math.imul(U,fe))+Math.imul(j,de)|0,o=Math.imul(j,fe);var Me=(u+(n=n+Math.imul(D,pe)|0)|0)+((8191&(i=(i=i+Math.imul(D,ge)|0)+Math.imul(L,pe)|0))<<13)|0;u=((o=o+Math.imul(L,ge)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863;var Re=(u+(n=Math.imul(U,pe))|0)+((8191&(i=(i=Math.imul(U,ge))+Math.imul(j,pe)|0))<<13)|0;return u=((o=Math.imul(j,ge))+(i>>>13)|0)+(Re>>>26)|0,Re&=67108863,c[0]=me,c[1]=ye,c[2]=be,c[3]=ve,c[4]=we,c[5]=_e,c[6]=Ee,c[7]=Se,c[8]=Te,c[9]=Ae,c[10]=Ie,c[11]=xe,c[12]=Oe,c[13]=ke,c[14]=Pe,c[15]=Ce,c[16]=Ne,c[17]=Me,c[18]=Re,0!==u&&(c[19]=u,r.length++),r};function y(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}r.words[o]=s,n=a,a=i}return 0!==n?r.words[o]=n:r.length--,r._strip()}function b(e,t,r){return y(e,t,r)}function v(e,t){this.x=e,this.y=t}Math.imul||(m=g),o.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?m(this,e,t):r<63?g(this,e,t):r<1024?y(this,e,t):b(this,e,t)},v.prototype.makeRBT=function(e){for(var t=new Array(e),r=o.prototype._countBits(e)-1,n=0;n>=1;return n},v.prototype.permute=function(e,t,r,n,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,r[2*a+1]=8191&o,o>>>=13;for(a=2*t;a>=26,r+=o/67108864|0,r+=a>>>26,this.words[i]=67108863&a}return 0!==r&&(this.words[i]=r,this.length++),t?this.ineg():this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i&1}return t}(e);if(0===t.length)return new o(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var a=0;for(t=0;t>>26-r}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,u=0;u=0&&(0!==l||u>=i);u--){var d=0|this.words[u];this.words[u]=l<<26-o|d>>>o,l=d&s}return c&&0!==l&&(c.words[c.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(c/67108864|0),this.words[i+r]=67108863&o}for(;i>26,this.words[i+r]=67108863&o;if(0===s)return this._strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this._strip()},o.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,a=0|i.words[i.length-1];0!=(r=26-this._countBits(a))&&(i=i.ushln(r),n.iushln(r),a=0|i.words[i.length-1]);var s,c=n.length-i.length;if("mod"!==t){(s=new o(null)).length=c+1,s.words=new Array(s.length);for(var u=0;u=0;d--){var f=67108864*(0|n.words[i.length+d])+(0|n.words[i.length+d-1]);for(f=Math.min(f/a|0,67108863),n._ishlnsubmul(i,f,d);0!==n.negative;)f--,n.negative=0,n._ishlnsubmul(i,1,d),n.isZero()||(n.negative^=1);s&&(s.words[d]=f)}return s&&s._strip(),n._strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modrn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=(1<<26)%e,i=0,o=this.length-1;o>=0;o--)i=(r*i+(0|this.words[o]))%e;return t?-i:i},o.prototype.modn=function(e){return this.modrn(e)},o.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=0,i=this.length-1;i>=0;i--){var o=(0|this.words[i])+67108864*r;this.words[i]=o/e|0,r=o%e}return this._strip(),t?this.ineg():this},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),c=new o(1),u=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++u;for(var l=r.clone(),d=t.clone();!t.isZero();){for(var f=0,h=1;0==(t.words[0]&h)&&f<26;++f,h<<=1);if(f>0)for(t.iushrn(f);f-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(l),a.isub(d)),i.iushrn(1),a.iushrn(1);for(var p=0,g=1;0==(r.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||c.isOdd())&&(s.iadd(l),c.isub(d)),s.iushrn(1),c.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(s),a.isub(c)):(r.isub(t),s.isub(i),c.isub(a))}return{a:s,b:c,gcd:r.iushln(u)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),c=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var u=0,l=1;0==(t.words[0]&l)&&u<26;++u,l<<=1);if(u>0)for(t.iushrn(u);u-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);for(var d=0,f=1;0==(r.words[0]&f)&&d<26;++d,f<<=1);if(d>0)for(r.iushrn(d);d-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(s)):(r.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this._strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new I(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var w={k256:null,p224:null,p192:null,p25519:null};function _(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function E(){_.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function S(){_.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function T(){_.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function A(){_.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function I(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function x(e){I.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}_.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},_.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},_.prototype.split=function(e,t){e.iushrn(this.n,0,t)},_.prototype.imulK=function(e){return e.imul(this.k)},i(E,_),E.prototype.split=function(e,t){for(var r=4194303,n=Math.min(e.length,9),i=0;i>>22,o=a}o>>>=22,e.words[i-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},E.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(w[e])return w[e];var t;if("k256"===e)t=new E;else if("p224"===e)t=new S;else if("p192"===e)t=new T;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new A}return w[e]=t,t},I.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},I.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},I.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(l(e,e.umod(this.m)._forceRed(this)),e)},I.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},I.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},I.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},I.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},I.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},I.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},I.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},I.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},I.prototype.isqr=function(e){return this.imul(e,e.clone())},I.prototype.sqr=function(e){return this.mul(e,e)},I.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);n(!i.isZero());var s=new o(1).toRed(this),c=s.redNeg(),u=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new o(2*l*l).toRed(this);0!==this.pow(l,u).cmp(c);)l.redIAdd(c);for(var d=this.pow(l,i),f=this.pow(e,i.addn(1).iushrn(1)),h=this.pow(e,i),p=a;0!==h.cmp(s);){for(var g=h,m=0;0!==g.cmp(s);m++)g=g.redSqr();n(m=0;n--){for(var u=t.words[n],l=c-1;l>=0;l--){var d=u>>l&1;i!==r[0]&&(i=this.sqr(i)),0!==d||0!==a?(a<<=1,a|=d,(4==++s||0===n&&0===l)&&(i=this.mul(i,r[a]),s=0,a=0)):s=0}c=26}return i},I.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},I.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new x(e)},i(x,I),x.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},x.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},x.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},x.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},x.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e=r.nmd(e),this)},43734:function(e,t,r){!function(e,t,r){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=n(t),o=n(r);function a(e,t){for(var r=0;r=4)throw new Error("Bootstrap's JavaScript requires at least jQuery v1.9.1 but less than v4.0.0")}};f.jQueryDetection(),i.default.fn.emulateTransitionEnd=d,i.default.event.special[f.TRANSITION_END]={bindType:l,delegateType:l,handle:function(e){if(i.default(e.target).is(this))return e.handleObj.handler.apply(this,arguments)}};var h="alert",p="bs.alert",g="."+p,m=i.default.fn[h],y="close"+g,b="closed"+g,v="click"+g+".data-api",w=function(){function e(e){this._element=e}var t=e.prototype;return t.close=function(e){var t=this._element;e&&(t=this._getRootElement(e)),this._triggerCloseEvent(t).isDefaultPrevented()||this._removeElement(t)},t.dispose=function(){i.default.removeData(this._element,p),this._element=null},t._getRootElement=function(e){var t=f.getSelectorFromElement(e),r=!1;return t&&(r=document.querySelector(t)),r||(r=i.default(e).closest(".alert")[0]),r},t._triggerCloseEvent=function(e){var t=i.default.Event(y);return i.default(e).trigger(t),t},t._removeElement=function(e){var t=this;if(i.default(e).removeClass("show"),i.default(e).hasClass("fade")){var r=f.getTransitionDurationFromElement(e);i.default(e).one(f.TRANSITION_END,(function(r){return t._destroyElement(e,r)})).emulateTransitionEnd(r)}else this._destroyElement(e)},t._destroyElement=function(e){i.default(e).detach().trigger(b).remove()},e._jQueryInterface=function(t){return this.each((function(){var r=i.default(this),n=r.data(p);n||(n=new e(this),r.data(p,n)),"close"===t&&n[t](this)}))},e._handleDismiss=function(e){return function(t){t&&t.preventDefault(),e.close(this)}},s(e,null,[{key:"VERSION",get:function(){return"4.6.2"}}]),e}();i.default(document).on(v,'[data-dismiss="alert"]',w._handleDismiss(new w)),i.default.fn[h]=w._jQueryInterface,i.default.fn[h].Constructor=w,i.default.fn[h].noConflict=function(){return i.default.fn[h]=m,w._jQueryInterface};var _="button",E="bs.button",S="."+E,T=".data-api",A=i.default.fn[_],I="active",x="click"+S+T,O="focus"+S+T+" blur"+S+T,k="load"+S+T,P='[data-toggle^="button"]',C='input:not([type="hidden"])',N=".btn",M=function(){function e(e){this._element=e,this.shouldAvoidTriggerChange=!1}var t=e.prototype;return t.toggle=function(){var e=!0,t=!0,r=i.default(this._element).closest('[data-toggle="buttons"]')[0];if(r){var n=this._element.querySelector(C);if(n){if("radio"===n.type)if(n.checked&&this._element.classList.contains(I))e=!1;else{var o=r.querySelector(".active");o&&i.default(o).removeClass(I)}e&&("checkbox"!==n.type&&"radio"!==n.type||(n.checked=!this._element.classList.contains(I)),this.shouldAvoidTriggerChange||i.default(n).trigger("change")),n.focus(),t=!1}}this._element.hasAttribute("disabled")||this._element.classList.contains("disabled")||(t&&this._element.setAttribute("aria-pressed",!this._element.classList.contains(I)),e&&i.default(this._element).toggleClass(I))},t.dispose=function(){i.default.removeData(this._element,E),this._element=null},e._jQueryInterface=function(t,r){return this.each((function(){var n=i.default(this),o=n.data(E);o||(o=new e(this),n.data(E,o)),o.shouldAvoidTriggerChange=r,"toggle"===t&&o[t]()}))},s(e,null,[{key:"VERSION",get:function(){return"4.6.2"}}]),e}();i.default(document).on(x,P,(function(e){var t=e.target,r=t;if(i.default(t).hasClass("btn")||(t=i.default(t).closest(N)[0]),!t||t.hasAttribute("disabled")||t.classList.contains("disabled"))e.preventDefault();else{var n=t.querySelector(C);if(n&&(n.hasAttribute("disabled")||n.classList.contains("disabled")))return void e.preventDefault();"INPUT"!==r.tagName&&"LABEL"===t.tagName||M._jQueryInterface.call(i.default(t),"toggle","INPUT"===r.tagName)}})).on(O,P,(function(e){var t=i.default(e.target).closest(N)[0];i.default(t).toggleClass("focus",/^focus(in)?$/.test(e.type))})),i.default(window).on(k,(function(){for(var e=[].slice.call(document.querySelectorAll('[data-toggle="buttons"] .btn')),t=0,r=e.length;t0,this._pointerEvent=Boolean(window.PointerEvent||window.MSPointerEvent),this._addEventListeners()}var t=e.prototype;return t.next=function(){this._isSliding||this._slide(F)},t.nextWhenVisible=function(){var e=i.default(this._element);!document.hidden&&e.is(":visible")&&"hidden"!==e.css("visibility")&&this.next()},t.prev=function(){this._isSliding||this._slide(H)},t.pause=function(e){e||(this._isPaused=!0),this._element.querySelector(".carousel-item-next, .carousel-item-prev")&&(f.triggerTransitionEnd(this._element),this.cycle(!0)),clearInterval(this._interval),this._interval=null},t.cycle=function(e){e||(this._isPaused=!1),this._interval&&(clearInterval(this._interval),this._interval=null),this._config.interval&&!this._isPaused&&(this._updateInterval(),this._interval=setInterval((document.visibilityState?this.nextWhenVisible:this.next).bind(this),this._config.interval))},t.to=function(e){var t=this;this._activeElement=this._element.querySelector(te);var r=this._getItemIndex(this._activeElement);if(!(e>this._items.length-1||e<0))if(this._isSliding)i.default(this._element).one(V,(function(){return t.to(e)}));else{if(r===e)return this.pause(),void this.cycle();var n=e>r?F:H;this._slide(n,this._items[e])}},t.dispose=function(){i.default(this._element).off(L),i.default.removeData(this._element,D),this._items=null,this._config=null,this._element=null,this._interval=null,this._isPaused=null,this._isSliding=null,this._activeElement=null,this._indicatorsElement=null},t._getConfig=function(e){return e=c({},re,e),f.typeCheckConfig(R,e,ne),e},t._handleSwipe=function(){var e=Math.abs(this.touchDeltaX);if(!(e<=40)){var t=e/this.touchDeltaX;this.touchDeltaX=0,t>0&&this.prev(),t<0&&this.next()}},t._addEventListeners=function(){var e=this;this._config.keyboard&&i.default(this._element).on($,(function(t){return e._keydown(t)})),"hover"===this._config.pause&&i.default(this._element).on(K,(function(t){return e.pause(t)})).on(q,(function(t){return e.cycle(t)})),this._config.touch&&this._addTouchEventListeners()},t._addTouchEventListeners=function(){var e=this;if(this._touchSupported){var t=function(t){e._pointerEvent&&ie[t.originalEvent.pointerType.toUpperCase()]?e.touchStartX=t.originalEvent.clientX:e._pointerEvent||(e.touchStartX=t.originalEvent.touches[0].clientX)},r=function(t){e._pointerEvent&&ie[t.originalEvent.pointerType.toUpperCase()]&&(e.touchDeltaX=t.originalEvent.clientX-e.touchStartX),e._handleSwipe(),"hover"===e._config.pause&&(e.pause(),e.touchTimeout&&clearTimeout(e.touchTimeout),e.touchTimeout=setTimeout((function(t){return e.cycle(t)}),500+e._config.interval))};i.default(this._element.querySelectorAll(".carousel-item img")).on(J,(function(e){return e.preventDefault()})),this._pointerEvent?(i.default(this._element).on(Y,(function(e){return t(e)})),i.default(this._element).on(Q,(function(e){return r(e)})),this._element.classList.add("pointer-event")):(i.default(this._element).on(z,(function(e){return t(e)})),i.default(this._element).on(G,(function(t){return function(t){e.touchDeltaX=t.originalEvent.touches&&t.originalEvent.touches.length>1?0:t.originalEvent.touches[0].clientX-e.touchStartX}(t)})),i.default(this._element).on(X,(function(e){return r(e)})))}},t._keydown=function(e){if(!/input|textarea/i.test(e.target.tagName))switch(e.which){case 37:e.preventDefault(),this.prev();break;case 39:e.preventDefault(),this.next()}},t._getItemIndex=function(e){return this._items=e&&e.parentNode?[].slice.call(e.parentNode.querySelectorAll(".carousel-item")):[],this._items.indexOf(e)},t._getItemByDirection=function(e,t){var r=e===F,n=e===H,i=this._getItemIndex(t),o=this._items.length-1;if((n&&0===i||r&&i===o)&&!this._config.wrap)return t;var a=(i+(e===H?-1:1))%this._items.length;return-1===a?this._items[this._items.length-1]:this._items[a]},t._triggerSlideEvent=function(e,t){var r=this._getItemIndex(e),n=this._getItemIndex(this._element.querySelector(te)),o=i.default.Event(W,{relatedTarget:e,direction:t,from:n,to:r});return i.default(this._element).trigger(o),o},t._setActiveIndicatorElement=function(e){if(this._indicatorsElement){var t=[].slice.call(this._indicatorsElement.querySelectorAll(".active"));i.default(t).removeClass(j);var r=this._indicatorsElement.children[this._getItemIndex(e)];r&&i.default(r).addClass(j)}},t._updateInterval=function(){var e=this._activeElement||this._element.querySelector(te);if(e){var t=parseInt(e.getAttribute("data-interval"),10);t?(this._config.defaultInterval=this._config.defaultInterval||this._config.interval,this._config.interval=t):this._config.interval=this._config.defaultInterval||this._config.interval}},t._slide=function(e,t){var r,n,o,a=this,s=this._element.querySelector(te),c=this._getItemIndex(s),u=t||s&&this._getItemByDirection(e,s),l=this._getItemIndex(u),d=Boolean(this._interval);if(e===F?(r="carousel-item-left",n="carousel-item-next",o="left"):(r="carousel-item-right",n="carousel-item-prev",o="right"),u&&i.default(u).hasClass(j))this._isSliding=!1;else if(!this._triggerSlideEvent(u,o).isDefaultPrevented()&&s&&u){this._isSliding=!0,d&&this.pause(),this._setActiveIndicatorElement(u),this._activeElement=u;var h=i.default.Event(V,{relatedTarget:u,direction:o,from:c,to:l});if(i.default(this._element).hasClass("slide")){i.default(u).addClass(n),f.reflow(u),i.default(s).addClass(r),i.default(u).addClass(r);var p=f.getTransitionDurationFromElement(s);i.default(s).one(f.TRANSITION_END,(function(){i.default(u).removeClass(r+" "+n).addClass(j),i.default(s).removeClass(j+" "+n+" "+r),a._isSliding=!1,setTimeout((function(){return i.default(a._element).trigger(h)}),0)})).emulateTransitionEnd(p)}else i.default(s).removeClass(j),i.default(u).addClass(j),this._isSliding=!1,i.default(this._element).trigger(h);d&&this.cycle()}},e._jQueryInterface=function(t){return this.each((function(){var r=i.default(this).data(D),n=c({},re,i.default(this).data());"object"==typeof t&&(n=c({},n,t));var o="string"==typeof t?t:n.slide;if(r||(r=new e(this,n),i.default(this).data(D,r)),"number"==typeof t)r.to(t);else if("string"==typeof o){if(void 0===r[o])throw new TypeError('No method named "'+o+'"');r[o]()}else n.interval&&n.ride&&(r.pause(),r.cycle())}))},e._dataApiClickHandler=function(t){var r=f.getSelectorFromElement(this);if(r){var n=i.default(r)[0];if(n&&i.default(n).hasClass("carousel")){var o=c({},i.default(n).data(),i.default(this).data()),a=this.getAttribute("data-slide-to");a&&(o.interval=!1),e._jQueryInterface.call(i.default(n),o),a&&i.default(n).data(D).to(a),t.preventDefault()}}},s(e,null,[{key:"VERSION",get:function(){return"4.6.2"}},{key:"Default",get:function(){return re}}]),e}();i.default(document).on(ee,"[data-slide], [data-slide-to]",oe._dataApiClickHandler),i.default(window).on(Z,(function(){for(var e=[].slice.call(document.querySelectorAll('[data-ride="carousel"]')),t=0,r=e.length;t0&&(this._selector=a,this._triggerArray.push(o))}this._parent=this._config.parent?this._getParent():null,this._config.parent||this._addAriaAndCollapsedClass(this._element,this._triggerArray),this._config.toggle&&this.toggle()}var t=e.prototype;return t.toggle=function(){i.default(this._element).hasClass(le)?this.hide():this.show()},t.show=function(){var t,r,n=this;if(!(this._isTransitioning||i.default(this._element).hasClass(le)||(this._parent&&0===(t=[].slice.call(this._parent.querySelectorAll(".show, .collapsing")).filter((function(e){return"string"==typeof n._config.parent?e.getAttribute("data-parent")===n._config.parent:e.classList.contains(de)}))).length&&(t=null),t&&(r=i.default(t).not(this._selector).data(se))&&r._isTransitioning))){var o=i.default.Event(ge);if(i.default(this._element).trigger(o),!o.isDefaultPrevented()){t&&(e._jQueryInterface.call(i.default(t).not(this._selector),"hide"),r||i.default(t).data(se,null));var a=this._getDimension();i.default(this._element).removeClass(de).addClass(fe),this._element.style[a]=0,this._triggerArray.length&&i.default(this._triggerArray).removeClass(he).attr("aria-expanded",!0),this.setTransitioning(!0);var s="scroll"+(a[0].toUpperCase()+a.slice(1)),c=f.getTransitionDurationFromElement(this._element);i.default(this._element).one(f.TRANSITION_END,(function(){i.default(n._element).removeClass(fe).addClass(de+" "+le),n._element.style[a]="",n.setTransitioning(!1),i.default(n._element).trigger(me)})).emulateTransitionEnd(c),this._element.style[a]=this._element[s]+"px"}}},t.hide=function(){var e=this;if(!this._isTransitioning&&i.default(this._element).hasClass(le)){var t=i.default.Event(ye);if(i.default(this._element).trigger(t),!t.isDefaultPrevented()){var r=this._getDimension();this._element.style[r]=this._element.getBoundingClientRect()[r]+"px",f.reflow(this._element),i.default(this._element).addClass(fe).removeClass(de+" "+le);var n=this._triggerArray.length;if(n>0)for(var o=0;o0},t._getOffset=function(){var e=this,t={};return"function"==typeof this._config.offset?t.fn=function(t){return t.offsets=c({},t.offsets,e._config.offset(t.offsets,e._element)),t}:t.offset=this._config.offset,t},t._getPopperConfig=function(){var e={placement:this._getPlacement(),modifiers:{offset:this._getOffset(),flip:{enabled:this._config.flip},preventOverflow:{boundariesElement:this._config.boundary}}};return"static"===this._config.display&&(e.modifiers.applyStyle={enabled:!1}),c({},e,this._config.popperConfig)},e._jQueryInterface=function(t){return this.each((function(){var r=i.default(this).data(Ae);if(r||(r=new e(this,"object"==typeof t?t:null),i.default(this).data(Ae,r)),"string"==typeof t){if(void 0===r[t])throw new TypeError('No method named "'+t+'"');r[t]()}}))},e._clearMenus=function(t){if(!t||3!==t.which&&("keyup"!==t.type||9===t.which))for(var r=[].slice.call(document.querySelectorAll(He)),n=0,o=r.length;n0&&a--,40===t.which&&adocument.documentElement.clientHeight;r||(this._element.style.overflowY="hidden"),this._element.classList.add(Ze);var n=f.getTransitionDurationFromElement(this._dialog);i.default(this._element).off(f.TRANSITION_END),i.default(this._element).one(f.TRANSITION_END,(function(){e._element.classList.remove(Ze),r||i.default(e._element).one(f.TRANSITION_END,(function(){e._element.style.overflowY=""})).emulateTransitionEnd(e._element,n)})).emulateTransitionEnd(n),this._element.focus()}},t._showElement=function(e){var t=this,r=i.default(this._element).hasClass(Qe),n=this._dialog?this._dialog.querySelector(".modal-body"):null;this._element.parentNode&&this._element.parentNode.nodeType===Node.ELEMENT_NODE||document.body.appendChild(this._element),this._element.style.display="block",this._element.removeAttribute("aria-hidden"),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),i.default(this._dialog).hasClass("modal-dialog-scrollable")&&n?n.scrollTop=0:this._element.scrollTop=0,r&&f.reflow(this._element),i.default(this._element).addClass(Je),this._config.focus&&this._enforceFocus();var o=i.default.Event(it,{relatedTarget:e}),a=function(){t._config.focus&&t._element.focus(),t._isTransitioning=!1,i.default(t._element).trigger(o)};if(r){var s=f.getTransitionDurationFromElement(this._dialog);i.default(this._dialog).one(f.TRANSITION_END,a).emulateTransitionEnd(s)}else a()},t._enforceFocus=function(){var e=this;i.default(document).off(ot).on(ot,(function(t){document!==t.target&&e._element!==t.target&&0===i.default(e._element).has(t.target).length&&e._element.focus()}))},t._setEscapeEvent=function(){var e=this;this._isShown?i.default(this._element).on(ct,(function(t){e._config.keyboard&&27===t.which?(t.preventDefault(),e.hide()):e._config.keyboard||27!==t.which||e._triggerBackdropTransition()})):this._isShown||i.default(this._element).off(ct)},t._setResizeEvent=function(){var e=this;this._isShown?i.default(window).on(at,(function(t){return e.handleUpdate(t)})):i.default(window).off(at)},t._hideModal=function(){var e=this;this._element.style.display="none",this._element.setAttribute("aria-hidden",!0),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._isTransitioning=!1,this._showBackdrop((function(){i.default(document.body).removeClass(Ye),e._resetAdjustments(),e._resetScrollbar(),i.default(e._element).trigger(rt)}))},t._removeBackdrop=function(){this._backdrop&&(i.default(this._backdrop).remove(),this._backdrop=null)},t._showBackdrop=function(e){var t=this,r=i.default(this._element).hasClass(Qe)?Qe:"";if(this._isShown&&this._config.backdrop){if(this._backdrop=document.createElement("div"),this._backdrop.className="modal-backdrop",r&&this._backdrop.classList.add(r),i.default(this._backdrop).appendTo(document.body),i.default(this._element).on(st,(function(e){t._ignoreBackdropClick?t._ignoreBackdropClick=!1:e.target===e.currentTarget&&("static"===t._config.backdrop?t._triggerBackdropTransition():t.hide())})),r&&f.reflow(this._backdrop),i.default(this._backdrop).addClass(Je),!e)return;if(!r)return void e();var n=f.getTransitionDurationFromElement(this._backdrop);i.default(this._backdrop).one(f.TRANSITION_END,e).emulateTransitionEnd(n)}else if(!this._isShown&&this._backdrop){i.default(this._backdrop).removeClass(Je);var o=function(){t._removeBackdrop(),e&&e()};if(i.default(this._element).hasClass(Qe)){var a=f.getTransitionDurationFromElement(this._backdrop);i.default(this._backdrop).one(f.TRANSITION_END,o).emulateTransitionEnd(a)}else o()}else e&&e()},t._adjustDialog=function(){var e=this._element.scrollHeight>document.documentElement.clientHeight;!this._isBodyOverflowing&&e&&(this._element.style.paddingLeft=this._scrollbarWidth+"px"),this._isBodyOverflowing&&!e&&(this._element.style.paddingRight=this._scrollbarWidth+"px")},t._resetAdjustments=function(){this._element.style.paddingLeft="",this._element.style.paddingRight=""},t._checkScrollbar=function(){var e=document.body.getBoundingClientRect();this._isBodyOverflowing=Math.round(e.left+e.right)
',trigger:"hover focus",title:"",delay:0,html:!1,selector:!1,placement:"top",offset:0,container:!1,fallbackPlacement:"flip",boundary:"scrollParent",customClass:"",sanitize:!0,sanitizeFn:null,whiteList:{"*":["class","dir","id","lang","role",/^aria-[\w-]*$/i],a:["target","href","title","rel"],area:[],b:[],br:[],col:[],code:[],div:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:["src","srcset","alt","title","width","height"],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},popperConfig:null},Lt={animation:"boolean",template:"string",title:"(string|element|function)",trigger:"string",delay:"(number|object)",html:"boolean",selector:"(string|boolean)",placement:"(string|function)",offset:"(number|string|function)",container:"(string|element|boolean)",fallbackPlacement:"(string|array)",boundary:"(string|element)",customClass:"(string|function)",sanitize:"boolean",sanitizeFn:"(null|function)",whiteList:"object",popperConfig:"(null|object)"},Bt={HIDE:"hide"+St,HIDDEN:"hidden"+St,SHOW:"show"+St,SHOWN:"shown"+St,INSERTED:"inserted"+St,CLICK:"click"+St,FOCUSIN:"focusin"+St,FOCUSOUT:"focusout"+St,MOUSEENTER:"mouseenter"+St,MOUSELEAVE:"mouseleave"+St},Ut=function(){function e(e,t){if(void 0===o.default)throw new TypeError("Bootstrap's tooltips require Popper (https://popper.js.org)");this._isEnabled=!0,this._timeout=0,this._hoverState="",this._activeTrigger={},this._popper=null,this.element=e,this.config=this._getConfig(t),this.tip=null,this._setListeners()}var t=e.prototype;return t.enable=function(){this._isEnabled=!0},t.disable=function(){this._isEnabled=!1},t.toggleEnabled=function(){this._isEnabled=!this._isEnabled},t.toggle=function(e){if(this._isEnabled)if(e){var t=this.constructor.DATA_KEY,r=i.default(e.currentTarget).data(t);r||(r=new this.constructor(e.currentTarget,this._getDelegateConfig()),i.default(e.currentTarget).data(t,r)),r._activeTrigger.click=!r._activeTrigger.click,r._isWithActiveTrigger()?r._enter(null,r):r._leave(null,r)}else{if(i.default(this.getTipElement()).hasClass(kt))return void this._leave(null,this);this._enter(null,this)}},t.dispose=function(){clearTimeout(this._timeout),i.default.removeData(this.element,this.constructor.DATA_KEY),i.default(this.element).off(this.constructor.EVENT_KEY),i.default(this.element).closest(".modal").off("hide.bs.modal",this._hideModalHandler),this.tip&&i.default(this.tip).remove(),this._isEnabled=null,this._timeout=null,this._hoverState=null,this._activeTrigger=null,this._popper&&this._popper.destroy(),this._popper=null,this.element=null,this.config=null,this.tip=null},t.show=function(){var e=this;if("none"===i.default(this.element).css("display"))throw new Error("Please use show on visible elements");var t=i.default.Event(this.constructor.Event.SHOW);if(this.isWithContent()&&this._isEnabled){i.default(this.element).trigger(t);var r=f.findShadowRoot(this.element),n=i.default.contains(null!==r?r:this.element.ownerDocument.documentElement,this.element);if(t.isDefaultPrevented()||!n)return;var a=this.getTipElement(),s=f.getUID(this.constructor.NAME);a.setAttribute("id",s),this.element.setAttribute("aria-describedby",s),this.setContent(),this.config.animation&&i.default(a).addClass(Ot);var c="function"==typeof this.config.placement?this.config.placement.call(this,a,this.element):this.config.placement,u=this._getAttachment(c);this.addAttachmentClass(u);var l=this._getContainer();i.default(a).data(this.constructor.DATA_KEY,this),i.default.contains(this.element.ownerDocument.documentElement,this.tip)||i.default(a).appendTo(l),i.default(this.element).trigger(this.constructor.Event.INSERTED),this._popper=new o.default(this.element,a,this._getPopperConfig(u)),i.default(a).addClass(kt),i.default(a).addClass(this.config.customClass),"ontouchstart"in document.documentElement&&i.default(document.body).children().on("mouseover",null,i.default.noop);var d=function(){e.config.animation&&e._fixTransition();var t=e._hoverState;e._hoverState=null,i.default(e.element).trigger(e.constructor.Event.SHOWN),t===Ct&&e._leave(null,e)};if(i.default(this.tip).hasClass(Ot)){var h=f.getTransitionDurationFromElement(this.tip);i.default(this.tip).one(f.TRANSITION_END,d).emulateTransitionEnd(h)}else d()}},t.hide=function(e){var t=this,r=this.getTipElement(),n=i.default.Event(this.constructor.Event.HIDE),o=function(){t._hoverState!==Pt&&r.parentNode&&r.parentNode.removeChild(r),t._cleanTipClass(),t.element.removeAttribute("aria-describedby"),i.default(t.element).trigger(t.constructor.Event.HIDDEN),null!==t._popper&&t._popper.destroy(),e&&e()};if(i.default(this.element).trigger(n),!n.isDefaultPrevented()){if(i.default(r).removeClass(kt),"ontouchstart"in document.documentElement&&i.default(document.body).children().off("mouseover",null,i.default.noop),this._activeTrigger.click=!1,this._activeTrigger[Mt]=!1,this._activeTrigger[Nt]=!1,i.default(this.tip).hasClass(Ot)){var a=f.getTransitionDurationFromElement(r);i.default(r).one(f.TRANSITION_END,o).emulateTransitionEnd(a)}else o();this._hoverState=""}},t.update=function(){null!==this._popper&&this._popper.scheduleUpdate()},t.isWithContent=function(){return Boolean(this.getTitle())},t.addAttachmentClass=function(e){i.default(this.getTipElement()).addClass(At+"-"+e)},t.getTipElement=function(){return this.tip=this.tip||i.default(this.config.template)[0],this.tip},t.setContent=function(){var e=this.getTipElement();this.setElementContent(i.default(e.querySelectorAll(".tooltip-inner")),this.getTitle()),i.default(e).removeClass(Ot+" "+kt)},t.setElementContent=function(e,t){"object"!=typeof t||!t.nodeType&&!t.jquery?this.config.html?(this.config.sanitize&&(t=wt(t,this.config.whiteList,this.config.sanitizeFn)),e.html(t)):e.text(t):this.config.html?i.default(t).parent().is(e)||e.empty().append(t):e.text(i.default(t).text())},t.getTitle=function(){var e=this.element.getAttribute("data-original-title");return e||(e="function"==typeof this.config.title?this.config.title.call(this.element):this.config.title),e},t._getPopperConfig=function(e){var t=this;return c({},{placement:e,modifiers:{offset:this._getOffset(),flip:{behavior:this.config.fallbackPlacement},arrow:{element:".arrow"},preventOverflow:{boundariesElement:this.config.boundary}},onCreate:function(e){e.originalPlacement!==e.placement&&t._handlePopperPlacementChange(e)},onUpdate:function(e){return t._handlePopperPlacementChange(e)}},this.config.popperConfig)},t._getOffset=function(){var e=this,t={};return"function"==typeof this.config.offset?t.fn=function(t){return t.offsets=c({},t.offsets,e.config.offset(t.offsets,e.element)),t}:t.offset=this.config.offset,t},t._getContainer=function(){return!1===this.config.container?document.body:f.isElement(this.config.container)?i.default(this.config.container):i.default(document).find(this.config.container)},t._getAttachment=function(e){return Rt[e.toUpperCase()]},t._setListeners=function(){var e=this;this.config.trigger.split(" ").forEach((function(t){if("click"===t)i.default(e.element).on(e.constructor.Event.CLICK,e.config.selector,(function(t){return e.toggle(t)}));else if("manual"!==t){var r=t===Nt?e.constructor.Event.MOUSEENTER:e.constructor.Event.FOCUSIN,n=t===Nt?e.constructor.Event.MOUSELEAVE:e.constructor.Event.FOCUSOUT;i.default(e.element).on(r,e.config.selector,(function(t){return e._enter(t)})).on(n,e.config.selector,(function(t){return e._leave(t)}))}})),this._hideModalHandler=function(){e.element&&e.hide()},i.default(this.element).closest(".modal").on("hide.bs.modal",this._hideModalHandler),this.config.selector?this.config=c({},this.config,{trigger:"manual",selector:""}):this._fixTitle()},t._fixTitle=function(){var e=typeof this.element.getAttribute("data-original-title");(this.element.getAttribute("title")||"string"!==e)&&(this.element.setAttribute("data-original-title",this.element.getAttribute("title")||""),this.element.setAttribute("title",""))},t._enter=function(e,t){var r=this.constructor.DATA_KEY;(t=t||i.default(e.currentTarget).data(r))||(t=new this.constructor(e.currentTarget,this._getDelegateConfig()),i.default(e.currentTarget).data(r,t)),e&&(t._activeTrigger["focusin"===e.type?Mt:Nt]=!0),i.default(t.getTipElement()).hasClass(kt)||t._hoverState===Pt?t._hoverState=Pt:(clearTimeout(t._timeout),t._hoverState=Pt,t.config.delay&&t.config.delay.show?t._timeout=setTimeout((function(){t._hoverState===Pt&&t.show()}),t.config.delay.show):t.show())},t._leave=function(e,t){var r=this.constructor.DATA_KEY;(t=t||i.default(e.currentTarget).data(r))||(t=new this.constructor(e.currentTarget,this._getDelegateConfig()),i.default(e.currentTarget).data(r,t)),e&&(t._activeTrigger["focusout"===e.type?Mt:Nt]=!1),t._isWithActiveTrigger()||(clearTimeout(t._timeout),t._hoverState=Ct,t.config.delay&&t.config.delay.hide?t._timeout=setTimeout((function(){t._hoverState===Ct&&t.hide()}),t.config.delay.hide):t.hide())},t._isWithActiveTrigger=function(){for(var e in this._activeTrigger)if(this._activeTrigger[e])return!0;return!1},t._getConfig=function(e){var t=i.default(this.element).data();return Object.keys(t).forEach((function(e){-1!==xt.indexOf(e)&&delete t[e]})),"number"==typeof(e=c({},this.constructor.Default,t,"object"==typeof e&&e?e:{})).delay&&(e.delay={show:e.delay,hide:e.delay}),"number"==typeof e.title&&(e.title=e.title.toString()),"number"==typeof e.content&&(e.content=e.content.toString()),f.typeCheckConfig(_t,e,this.constructor.DefaultType),e.sanitize&&(e.template=wt(e.template,e.whiteList,e.sanitizeFn)),e},t._getDelegateConfig=function(){var e={};if(this.config)for(var t in this.config)this.constructor.Default[t]!==this.config[t]&&(e[t]=this.config[t]);return e},t._cleanTipClass=function(){var e=i.default(this.getTipElement()),t=e.attr("class").match(It);null!==t&&t.length&&e.removeClass(t.join(""))},t._handlePopperPlacementChange=function(e){this.tip=e.instance.popper,this._cleanTipClass(),this.addAttachmentClass(this._getAttachment(e.placement))},t._fixTransition=function(){var e=this.getTipElement(),t=this.config.animation;null===e.getAttribute("x-placement")&&(i.default(e).removeClass(Ot),this.config.animation=!1,this.hide(),this.show(),this.config.animation=t)},e._jQueryInterface=function(t){return this.each((function(){var r=i.default(this),n=r.data(Et),o="object"==typeof t&&t;if((n||!/dispose|hide/.test(t))&&(n||(n=new e(this,o),r.data(Et,n)),"string"==typeof t)){if(void 0===n[t])throw new TypeError('No method named "'+t+'"');n[t]()}}))},s(e,null,[{key:"VERSION",get:function(){return"4.6.2"}},{key:"Default",get:function(){return Dt}},{key:"NAME",get:function(){return _t}},{key:"DATA_KEY",get:function(){return Et}},{key:"Event",get:function(){return Bt}},{key:"EVENT_KEY",get:function(){return St}},{key:"DefaultType",get:function(){return Lt}}]),e}();i.default.fn[_t]=Ut._jQueryInterface,i.default.fn[_t].Constructor=Ut,i.default.fn[_t].noConflict=function(){return i.default.fn[_t]=Tt,Ut._jQueryInterface};var jt="popover",Ft="bs.popover",Ht="."+Ft,Wt=i.default.fn[jt],Vt="bs-popover",$t=new RegExp("(^|\\s)"+Vt+"\\S+","g"),Kt=c({},Ut.Default,{placement:"right",trigger:"click",content:"",template:''}),qt=c({},Ut.DefaultType,{content:"(string|element|function)"}),zt={HIDE:"hide"+Ht,HIDDEN:"hidden"+Ht,SHOW:"show"+Ht,SHOWN:"shown"+Ht,INSERTED:"inserted"+Ht,CLICK:"click"+Ht,FOCUSIN:"focusin"+Ht,FOCUSOUT:"focusout"+Ht,MOUSEENTER:"mouseenter"+Ht,MOUSELEAVE:"mouseleave"+Ht},Gt=function(e){function t(){return e.apply(this,arguments)||this}var r,n;n=e,(r=t).prototype=Object.create(n.prototype),r.prototype.constructor=r,u(r,n);var o=t.prototype;return o.isWithContent=function(){return this.getTitle()||this._getContent()},o.addAttachmentClass=function(e){i.default(this.getTipElement()).addClass(Vt+"-"+e)},o.getTipElement=function(){return this.tip=this.tip||i.default(this.config.template)[0],this.tip},o.setContent=function(){var e=i.default(this.getTipElement());this.setElementContent(e.find(".popover-header"),this.getTitle());var t=this._getContent();"function"==typeof t&&(t=t.call(this.element)),this.setElementContent(e.find(".popover-body"),t),e.removeClass("fade show")},o._getContent=function(){return this.element.getAttribute("data-content")||this.config.content},o._cleanTipClass=function(){var e=i.default(this.getTipElement()),t=e.attr("class").match($t);null!==t&&t.length>0&&e.removeClass(t.join(""))},t._jQueryInterface=function(e){return this.each((function(){var r=i.default(this).data(Ft),n="object"==typeof e?e:null;if((r||!/dispose|hide/.test(e))&&(r||(r=new t(this,n),i.default(this).data(Ft,r)),"string"==typeof e)){if(void 0===r[e])throw new TypeError('No method named "'+e+'"');r[e]()}}))},s(t,null,[{key:"VERSION",get:function(){return"4.6.2"}},{key:"Default",get:function(){return Kt}},{key:"NAME",get:function(){return jt}},{key:"DATA_KEY",get:function(){return Ft}},{key:"Event",get:function(){return zt}},{key:"EVENT_KEY",get:function(){return Ht}},{key:"DefaultType",get:function(){return qt}}]),t}(Ut);i.default.fn[jt]=Gt._jQueryInterface,i.default.fn[jt].Constructor=Gt,i.default.fn[jt].noConflict=function(){return i.default.fn[jt]=Wt,Gt._jQueryInterface};var Xt="scrollspy",Yt="bs.scrollspy",Qt="."+Yt,Jt=i.default.fn[Xt],Zt="active",er="activate"+Qt,tr="scroll"+Qt,rr="load"+Qt+".data-api",nr="position",ir=".nav, .list-group",or=".nav-link",ar=".list-group-item",sr={offset:10,method:"auto",target:""},cr={offset:"number",method:"string",target:"(string|element)"},ur=function(){function e(e,t){var r=this;this._element=e,this._scrollElement="BODY"===e.tagName?window:e,this._config=this._getConfig(t),this._selector=this._config.target+" "+or+","+this._config.target+" "+ar+","+this._config.target+" .dropdown-item",this._offsets=[],this._targets=[],this._activeTarget=null,this._scrollHeight=0,i.default(this._scrollElement).on(tr,(function(e){return r._process(e)})),this.refresh(),this._process()}var t=e.prototype;return t.refresh=function(){var e=this,t=this._scrollElement===this._scrollElement.window?"offset":nr,r="auto"===this._config.method?t:this._config.method,n=r===nr?this._getScrollTop():0;this._offsets=[],this._targets=[],this._scrollHeight=this._getScrollHeight(),[].slice.call(document.querySelectorAll(this._selector)).map((function(e){var t,o=f.getSelectorFromElement(e);if(o&&(t=document.querySelector(o)),t){var a=t.getBoundingClientRect();if(a.width||a.height)return[i.default(t)[r]().top+n,o]}return null})).filter(Boolean).sort((function(e,t){return e[0]-t[0]})).forEach((function(t){e._offsets.push(t[0]),e._targets.push(t[1])}))},t.dispose=function(){i.default.removeData(this._element,Yt),i.default(this._scrollElement).off(Qt),this._element=null,this._scrollElement=null,this._config=null,this._selector=null,this._offsets=null,this._targets=null,this._activeTarget=null,this._scrollHeight=null},t._getConfig=function(e){if("string"!=typeof(e=c({},sr,"object"==typeof e&&e?e:{})).target&&f.isElement(e.target)){var t=i.default(e.target).attr("id");t||(t=f.getUID(Xt),i.default(e.target).attr("id",t)),e.target="#"+t}return f.typeCheckConfig(Xt,e,cr),e},t._getScrollTop=function(){return this._scrollElement===window?this._scrollElement.pageYOffset:this._scrollElement.scrollTop},t._getScrollHeight=function(){return this._scrollElement.scrollHeight||Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)},t._getOffsetHeight=function(){return this._scrollElement===window?window.innerHeight:this._scrollElement.getBoundingClientRect().height},t._process=function(){var e=this._getScrollTop()+this._config.offset,t=this._getScrollHeight(),r=this._config.offset+t-this._getOffsetHeight();if(this._scrollHeight!==t&&this.refresh(),e>=r){var n=this._targets[this._targets.length-1];this._activeTarget!==n&&this._activate(n)}else{if(this._activeTarget&&e0)return this._activeTarget=null,void this._clear();for(var i=this._offsets.length;i--;)this._activeTarget!==this._targets[i]&&e>=this._offsets[i]&&(void 0===this._offsets[i+1]||e li > .active",Tr=function(){function e(e){this._element=e}var t=e.prototype;return t.show=function(){var e=this;if(!(this._element.parentNode&&this._element.parentNode.nodeType===Node.ELEMENT_NODE&&i.default(this._element).hasClass(pr)||i.default(this._element).hasClass("disabled")||this._element.hasAttribute("disabled"))){var t,r,n=i.default(this._element).closest(".nav, .list-group")[0],o=f.getSelectorFromElement(this._element);if(n){var a="UL"===n.nodeName||"OL"===n.nodeName?Sr:Er;r=(r=i.default.makeArray(i.default(n).find(a)))[r.length-1]}var s=i.default.Event(yr,{relatedTarget:this._element}),c=i.default.Event(vr,{relatedTarget:r});if(r&&i.default(r).trigger(s),i.default(this._element).trigger(c),!c.isDefaultPrevented()&&!s.isDefaultPrevented()){o&&(t=document.querySelector(o)),this._activate(this._element,n);var u=function(){var t=i.default.Event(br,{relatedTarget:e._element}),n=i.default.Event(wr,{relatedTarget:r});i.default(r).trigger(t),i.default(e._element).trigger(n)};t?this._activate(t,t.parentNode,u):u()}}},t.dispose=function(){i.default.removeData(this._element,dr),this._element=null},t._activate=function(e,t,r){var n=this,o=(!t||"UL"!==t.nodeName&&"OL"!==t.nodeName?i.default(t).children(Er):i.default(t).find(Sr))[0],a=r&&o&&i.default(o).hasClass(gr),s=function(){return n._transitionComplete(e,o,r)};if(o&&a){var c=f.getTransitionDurationFromElement(o);i.default(o).removeClass(mr).one(f.TRANSITION_END,s).emulateTransitionEnd(c)}else s()},t._transitionComplete=function(e,t,r){if(t){i.default(t).removeClass(pr);var n=i.default(t.parentNode).find("> .dropdown-menu .active")[0];n&&i.default(n).removeClass(pr),"tab"===t.getAttribute("role")&&t.setAttribute("aria-selected",!1)}i.default(e).addClass(pr),"tab"===e.getAttribute("role")&&e.setAttribute("aria-selected",!0),f.reflow(e),e.classList.contains(gr)&&e.classList.add(mr);var o=e.parentNode;if(o&&"LI"===o.nodeName&&(o=o.parentNode),o&&i.default(o).hasClass("dropdown-menu")){var a=i.default(e).closest(".dropdown")[0];if(a){var s=[].slice.call(a.querySelectorAll(".dropdown-toggle"));i.default(s).addClass(pr)}e.setAttribute("aria-expanded",!0)}r&&r()},e._jQueryInterface=function(t){return this.each((function(){var r=i.default(this),n=r.data(dr);if(n||(n=new e(this),r.data(dr,n)),"string"==typeof t){if(void 0===n[t])throw new TypeError('No method named "'+t+'"');n[t]()}}))},s(e,null,[{key:"VERSION",get:function(){return"4.6.2"}}]),e}();i.default(document).on(_r,'[data-toggle="tab"], [data-toggle="pill"], [data-toggle="list"]',(function(e){e.preventDefault(),Tr._jQueryInterface.call(i.default(this),"show")})),i.default.fn[lr]=Tr._jQueryInterface,i.default.fn[lr].Constructor=Tr,i.default.fn[lr].noConflict=function(){return i.default.fn[lr]=hr,Tr._jQueryInterface};var Ar="toast",Ir="bs.toast",xr="."+Ir,Or=i.default.fn[Ar],kr="hide",Pr="show",Cr="showing",Nr="click.dismiss"+xr,Mr="hide"+xr,Rr="hidden"+xr,Dr="show"+xr,Lr="shown"+xr,Br={animation:!0,autohide:!0,delay:500},Ur={animation:"boolean",autohide:"boolean",delay:"number"},jr=function(){function e(e,t){this._element=e,this._config=this._getConfig(t),this._timeout=null,this._setListeners()}var t=e.prototype;return t.show=function(){var e=this,t=i.default.Event(Dr);if(i.default(this._element).trigger(t),!t.isDefaultPrevented()){this._clearTimeout(),this._config.animation&&this._element.classList.add("fade");var r=function(){e._element.classList.remove(Cr),e._element.classList.add(Pr),i.default(e._element).trigger(Lr),e._config.autohide&&(e._timeout=setTimeout((function(){e.hide()}),e._config.delay))};if(this._element.classList.remove(kr),f.reflow(this._element),this._element.classList.add(Cr),this._config.animation){var n=f.getTransitionDurationFromElement(this._element);i.default(this._element).one(f.TRANSITION_END,r).emulateTransitionEnd(n)}else r()}},t.hide=function(){if(this._element.classList.contains(Pr)){var e=i.default.Event(Mr);i.default(this._element).trigger(e),e.isDefaultPrevented()||this._close()}},t.dispose=function(){this._clearTimeout(),this._element.classList.contains(Pr)&&this._element.classList.remove(Pr),i.default(this._element).off(Nr),i.default.removeData(this._element,Ir),this._element=null,this._config=null},t._getConfig=function(e){return e=c({},Br,i.default(this._element).data(),"object"==typeof e&&e?e:{}),f.typeCheckConfig(Ar,e,this.constructor.DefaultType),e},t._setListeners=function(){var e=this;i.default(this._element).on(Nr,'[data-dismiss="toast"]',(function(){return e.hide()}))},t._close=function(){var e=this,t=function(){e._element.classList.add(kr),i.default(e._element).trigger(Rr)};if(this._element.classList.remove(Pr),this._config.animation){var r=f.getTransitionDurationFromElement(this._element);i.default(this._element).one(f.TRANSITION_END,t).emulateTransitionEnd(r)}else t()},t._clearTimeout=function(){clearTimeout(this._timeout),this._timeout=null},e._jQueryInterface=function(t){return this.each((function(){var r=i.default(this),n=r.data(Ir);if(n||(n=new e(this,"object"==typeof t&&t),r.data(Ir,n)),"string"==typeof t){if(void 0===n[t])throw new TypeError('No method named "'+t+'"');n[t](this)}}))},s(e,null,[{key:"VERSION",get:function(){return"4.6.2"}},{key:"DefaultType",get:function(){return Ur}},{key:"Default",get:function(){return Br}}]),e}();i.default.fn[Ar]=jr._jQueryInterface,i.default.fn[Ar].Constructor=jr,i.default.fn[Ar].noConflict=function(){return i.default.fn[Ar]=Or,jr._jQueryInterface},e.Alert=w,e.Button=M,e.Carousel=oe,e.Collapse=Se,e.Dropdown=Ke,e.Modal=mt,e.Popover=Gt,e.Scrollspy=ur,e.Tab=Tr,e.Toast=jr,e.Tooltip=Ut,e.Util=f,Object.defineProperty(e,"__esModule",{value:!0})}(t,r(19755),r(28981))},29931:(e,t,r)=>{var n;function i(e){this.rand=e}if(e.exports=function(e){return n||(n=new i(null)),n.generate(e)},e.exports.Rand=i,i.prototype.generate=function(e){return this._rand(e)},i.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),r=0;r{var n=r(89509).Buffer;function i(e){n.isBuffer(e)||(e=n.from(e));for(var t=e.length/4|0,r=new Array(t),i=0;i>>24]^l[p>>>16&255]^d[g>>>8&255]^f[255&m]^t[y++],a=u[p>>>24]^l[g>>>16&255]^d[m>>>8&255]^f[255&h]^t[y++],s=u[g>>>24]^l[m>>>16&255]^d[h>>>8&255]^f[255&p]^t[y++],c=u[m>>>24]^l[h>>>16&255]^d[p>>>8&255]^f[255&g]^t[y++],h=o,p=a,g=s,m=c;return o=(n[h>>>24]<<24|n[p>>>16&255]<<16|n[g>>>8&255]<<8|n[255&m])^t[y++],a=(n[p>>>24]<<24|n[g>>>16&255]<<16|n[m>>>8&255]<<8|n[255&h])^t[y++],s=(n[g>>>24]<<24|n[m>>>16&255]<<16|n[h>>>8&255]<<8|n[255&p])^t[y++],c=(n[m>>>24]<<24|n[h>>>16&255]<<16|n[p>>>8&255]<<8|n[255&g])^t[y++],[o>>>=0,a>>>=0,s>>>=0,c>>>=0]}var s=[0,1,2,4,8,16,32,64,128,27,54],c=function(){for(var e=new Array(256),t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var r=[],n=[],i=[[],[],[],[]],o=[[],[],[],[]],a=0,s=0,c=0;c<256;++c){var u=s^s<<1^s<<2^s<<3^s<<4;u=u>>>8^255&u^99,r[a]=u,n[u]=a;var l=e[a],d=e[l],f=e[d],h=257*e[u]^16843008*u;i[0][a]=h<<24|h>>>8,i[1][a]=h<<16|h>>>16,i[2][a]=h<<8|h>>>24,i[3][a]=h,h=16843009*f^65537*d^257*l^16843008*a,o[0][u]=h<<24|h>>>8,o[1][u]=h<<16|h>>>16,o[2][u]=h<<8|h>>>24,o[3][u]=h,0===a?a=s=1:(a=l^e[e[e[f^l]]],s^=e[e[s]])}return{SBOX:r,INV_SBOX:n,SUB_MIX:i,INV_SUB_MIX:o}}();function u(e){this._key=i(e),this._reset()}u.blockSize=16,u.keySize=32,u.prototype.blockSize=u.blockSize,u.prototype.keySize=u.keySize,u.prototype._reset=function(){for(var e=this._key,t=e.length,r=t+6,n=4*(r+1),i=[],o=0;o>>24,a=c.SBOX[a>>>24]<<24|c.SBOX[a>>>16&255]<<16|c.SBOX[a>>>8&255]<<8|c.SBOX[255&a],a^=s[o/t|0]<<24):t>6&&o%t==4&&(a=c.SBOX[a>>>24]<<24|c.SBOX[a>>>16&255]<<16|c.SBOX[a>>>8&255]<<8|c.SBOX[255&a]),i[o]=i[o-t]^a}for(var u=[],l=0;l>>24]]^c.INV_SUB_MIX[1][c.SBOX[f>>>16&255]]^c.INV_SUB_MIX[2][c.SBOX[f>>>8&255]]^c.INV_SUB_MIX[3][c.SBOX[255&f]]}this._nRounds=r,this._keySchedule=i,this._invKeySchedule=u},u.prototype.encryptBlockRaw=function(e){return a(e=i(e),this._keySchedule,c.SUB_MIX,c.SBOX,this._nRounds)},u.prototype.encryptBlock=function(e){var t=this.encryptBlockRaw(e),r=n.allocUnsafe(16);return r.writeUInt32BE(t[0],0),r.writeUInt32BE(t[1],4),r.writeUInt32BE(t[2],8),r.writeUInt32BE(t[3],12),r},u.prototype.decryptBlock=function(e){var t=(e=i(e))[1];e[1]=e[3],e[3]=t;var r=a(e,this._invKeySchedule,c.INV_SUB_MIX,c.INV_SBOX,this._nRounds),o=n.allocUnsafe(16);return o.writeUInt32BE(r[0],0),o.writeUInt32BE(r[3],4),o.writeUInt32BE(r[2],8),o.writeUInt32BE(r[1],12),o},u.prototype.scrub=function(){o(this._keySchedule),o(this._invKeySchedule),o(this._key)},e.exports.AES=u},62422:(e,t,r)=>{var n=r(74497),i=r(89509).Buffer,o=r(71027),a=r(35717),s=r(83288),c=r(67295),u=r(20685);function l(e,t,r,a){o.call(this);var c=i.alloc(4,0);this._cipher=new n.AES(t);var l=this._cipher.encryptBlock(c);this._ghash=new s(l),r=function(e,t,r){if(12===t.length)return e._finID=i.concat([t,i.from([0,0,0,1])]),i.concat([t,i.from([0,0,0,2])]);var n=new s(r),o=t.length,a=o%16;n.update(t),a&&(a=16-a,n.update(i.alloc(a,0))),n.update(i.alloc(8,0));var c=8*o,l=i.alloc(8);l.writeUIntBE(c,0,8),n.update(l),e._finID=n.state;var d=i.from(e._finID);return u(d),d}(this,r,l),this._prev=i.from(r),this._cache=i.allocUnsafe(0),this._secCache=i.allocUnsafe(0),this._decrypt=a,this._alen=0,this._len=0,this._mode=e,this._authTag=null,this._called=!1}a(l,o),l.prototype._update=function(e){if(!this._called&&this._alen){var t=16-this._alen%16;t<16&&(t=i.alloc(t,0),this._ghash.update(t))}this._called=!0;var r=this._mode.encrypt(this,e);return this._decrypt?this._ghash.update(e):this._ghash.update(r),this._len+=e.length,r},l.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var e=c(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&function(e,t){var r=0;e.length!==t.length&&r++;for(var n=Math.min(e.length,t.length),i=0;i{var n=r(71494),i=r(66193),o=r(44946);t.createCipher=t.Cipher=n.createCipher,t.createCipheriv=t.Cipheriv=n.createCipheriv,t.createDecipher=t.Decipher=i.createDecipher,t.createDecipheriv=t.Decipheriv=i.createDecipheriv,t.listCiphers=t.getCiphers=function(){return Object.keys(o)}},66193:(e,t,r)=>{var n=r(62422),i=r(89509).Buffer,o=r(45),a=r(25969),s=r(71027),c=r(74497),u=r(13048);function l(e,t,r){s.call(this),this._cache=new d,this._last=void 0,this._cipher=new c.AES(t),this._prev=i.from(r),this._mode=e,this._autopadding=!0}function d(){this.cache=i.allocUnsafe(0)}function f(e,t,r){var s=o[e.toLowerCase()];if(!s)throw new TypeError("invalid suite type");if("string"==typeof r&&(r=i.from(r)),"GCM"!==s.mode&&r.length!==s.iv)throw new TypeError("invalid iv length "+r.length);if("string"==typeof t&&(t=i.from(t)),t.length!==s.key/8)throw new TypeError("invalid key length "+t.length);return"stream"===s.type?new a(s.module,t,r,!0):"auth"===s.type?new n(s.module,t,r,!0):new l(s.module,t,r)}r(35717)(l,s),l.prototype._update=function(e){var t,r;this._cache.add(e);for(var n=[];t=this._cache.get(this._autopadding);)r=this._mode.decrypt(this,t),n.push(r);return i.concat(n)},l.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return function(e){var t=e[15];if(t<1||t>16)throw new Error("unable to decrypt data");for(var r=-1;++r16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t}else if(this.cache.length>=16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t;return null},d.prototype.flush=function(){if(this.cache.length)return this.cache},t.createDecipher=function(e,t){var r=o[e.toLowerCase()];if(!r)throw new TypeError("invalid suite type");var n=u(t,!1,r.key,r.iv);return f(e,n.key,n.iv)},t.createDecipheriv=f},71494:(e,t,r)=>{var n=r(45),i=r(62422),o=r(89509).Buffer,a=r(25969),s=r(71027),c=r(74497),u=r(13048);function l(e,t,r){s.call(this),this._cache=new f,this._cipher=new c.AES(t),this._prev=o.from(r),this._mode=e,this._autopadding=!0}r(35717)(l,s),l.prototype._update=function(e){var t,r;this._cache.add(e);for(var n=[];t=this._cache.get();)r=this._mode.encrypt(this,t),n.push(r);return o.concat(n)};var d=o.alloc(16,16);function f(){this.cache=o.allocUnsafe(0)}function h(e,t,r){var s=n[e.toLowerCase()];if(!s)throw new TypeError("invalid suite type");if("string"==typeof t&&(t=o.from(t)),t.length!==s.key/8)throw new TypeError("invalid key length "+t.length);if("string"==typeof r&&(r=o.from(r)),"GCM"!==s.mode&&r.length!==s.iv)throw new TypeError("invalid iv length "+r.length);return"stream"===s.type?new a(s.module,t,r):"auth"===s.type?new i(s.module,t,r):new l(s.module,t,r)}l.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return e=this._mode.encrypt(this,e),this._cipher.scrub(),e;if(!e.equals(d))throw this._cipher.scrub(),new Error("data not multiple of block length")},l.prototype.setAutoPadding=function(e){return this._autopadding=!!e,this},f.prototype.add=function(e){this.cache=o.concat([this.cache,e])},f.prototype.get=function(){if(this.cache.length>15){var e=this.cache.slice(0,16);return this.cache=this.cache.slice(16),e}return null},f.prototype.flush=function(){for(var e=16-this.cache.length,t=o.allocUnsafe(e),r=-1;++r{var n=r(89509).Buffer,i=n.alloc(16,0);function o(e){var t=n.allocUnsafe(16);return t.writeUInt32BE(e[0]>>>0,0),t.writeUInt32BE(e[1]>>>0,4),t.writeUInt32BE(e[2]>>>0,8),t.writeUInt32BE(e[3]>>>0,12),t}function a(e){this.h=e,this.state=n.alloc(16,0),this.cache=n.allocUnsafe(0)}a.prototype.ghash=function(e){for(var t=-1;++t0;t--)n[t]=n[t]>>>1|(1&n[t-1])<<31;n[0]=n[0]>>>1,r&&(n[0]=n[0]^225<<24)}this.state=o(i)},a.prototype.update=function(e){var t;for(this.cache=n.concat([this.cache,e]);this.cache.length>=16;)t=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(t)},a.prototype.final=function(e,t){return this.cache.length&&this.ghash(n.concat([this.cache,i],16)),this.ghash(o([0,e,0,t])),this.state},e.exports=a},20685:e=>{e.exports=function(e){for(var t,r=e.length;r--;){if(255!==(t=e.readUInt8(r))){t++,e.writeUInt8(t,r);break}e.writeUInt8(0,r)}}},25292:(e,t,r)=>{var n=r(67295);t.encrypt=function(e,t){var r=n(t,e._prev);return e._prev=e._cipher.encryptBlock(r),e._prev},t.decrypt=function(e,t){var r=e._prev;e._prev=t;var i=e._cipher.decryptBlock(t);return n(i,r)}},86311:(e,t,r)=>{var n=r(89509).Buffer,i=r(67295);function o(e,t,r){var o=t.length,a=i(t,e._cache);return e._cache=e._cache.slice(o),e._prev=n.concat([e._prev,r?t:a]),a}t.encrypt=function(e,t,r){for(var i,a=n.allocUnsafe(0);t.length;){if(0===e._cache.length&&(e._cache=e._cipher.encryptBlock(e._prev),e._prev=n.allocUnsafe(0)),!(e._cache.length<=t.length)){a=n.concat([a,o(e,t,r)]);break}i=e._cache.length,a=n.concat([a,o(e,t.slice(0,i),r)]),t=t.slice(i)}return a}},21510:(e,t,r)=>{var n=r(89509).Buffer;function i(e,t,r){for(var n,i,a=-1,s=0;++a<8;)n=t&1<<7-a?128:0,s+=(128&(i=e._cipher.encryptBlock(e._prev)[0]^n))>>a%8,e._prev=o(e._prev,r?n:i);return s}function o(e,t){var r=e.length,i=-1,o=n.allocUnsafe(e.length);for(e=n.concat([e,n.from([t])]);++i>7;return o}t.encrypt=function(e,t,r){for(var o=t.length,a=n.allocUnsafe(o),s=-1;++s{var n=r(89509).Buffer;function i(e,t,r){var i=e._cipher.encryptBlock(e._prev)[0]^t;return e._prev=n.concat([e._prev.slice(1),n.from([r?t:i])]),i}t.encrypt=function(e,t,r){for(var o=t.length,a=n.allocUnsafe(o),s=-1;++s{var n=r(67295),i=r(89509).Buffer,o=r(20685);function a(e){var t=e._cipher.encryptBlockRaw(e._prev);return o(e._prev),t}t.encrypt=function(e,t){var r=Math.ceil(t.length/16),o=e._cache.length;e._cache=i.concat([e._cache,i.allocUnsafe(16*r)]);for(var s=0;s{t.encrypt=function(e,t){return e._cipher.encryptBlock(t)},t.decrypt=function(e,t){return e._cipher.decryptBlock(t)}},45:(e,t,r)=>{var n={ECB:r(11084),CBC:r(25292),CFB:r(86311),CFB8:r(71964),CFB1:r(21510),OFB:r(18861),CTR:r(96009),GCM:r(96009)},i=r(44946);for(var o in i)i[o].module=n[i[o].mode];e.exports=i},18861:(e,t,r)=>{var n=r(48764).Buffer,i=r(67295);function o(e){return e._prev=e._cipher.encryptBlock(e._prev),e._prev}t.encrypt=function(e,t){for(;e._cache.length{var n=r(74497),i=r(89509).Buffer,o=r(71027);function a(e,t,r,a){o.call(this),this._cipher=new n.AES(t),this._prev=i.from(r),this._cache=i.allocUnsafe(0),this._secCache=i.allocUnsafe(0),this._decrypt=a,this._mode=e}r(35717)(a,o),a.prototype._update=function(e){return this._mode.encrypt(this,e,this._decrypt)},a.prototype._final=function(){this._cipher.scrub()},e.exports=a},53614:(e,t,r)=>{var n=r(47667),i=r(44696),o=r(45),a=r(99715),s=r(13048);function c(e,t,r){if(e=e.toLowerCase(),o[e])return i.createCipheriv(e,t,r);if(a[e])return new n({key:t,iv:r,mode:e});throw new TypeError("invalid suite type")}function u(e,t,r){if(e=e.toLowerCase(),o[e])return i.createDecipheriv(e,t,r);if(a[e])return new n({key:t,iv:r,mode:e,decrypt:!0});throw new TypeError("invalid suite type")}t.createCipher=t.Cipher=function(e,t){var r,n;if(e=e.toLowerCase(),o[e])r=o[e].key,n=o[e].iv;else{if(!a[e])throw new TypeError("invalid suite type");r=8*a[e].key,n=a[e].iv}var i=s(t,!1,r,n);return c(e,i.key,i.iv)},t.createCipheriv=t.Cipheriv=c,t.createDecipher=t.Decipher=function(e,t){var r,n;if(e=e.toLowerCase(),o[e])r=o[e].key,n=o[e].iv;else{if(!a[e])throw new TypeError("invalid suite type");r=8*a[e].key,n=a[e].iv}var i=s(t,!1,r,n);return u(e,i.key,i.iv)},t.createDecipheriv=t.Decipheriv=u,t.listCiphers=t.getCiphers=function(){return Object.keys(a).concat(i.getCiphers())}},47667:(e,t,r)=>{var n=r(71027),i=r(15251),o=r(35717),a=r(89509).Buffer,s={"des-ede3-cbc":i.CBC.instantiate(i.EDE),"des-ede3":i.EDE,"des-ede-cbc":i.CBC.instantiate(i.EDE),"des-ede":i.EDE,"des-cbc":i.CBC.instantiate(i.DES),"des-ecb":i.DES};function c(e){n.call(this);var t,r=e.mode.toLowerCase(),i=s[r];t=e.decrypt?"decrypt":"encrypt";var o=e.key;a.isBuffer(o)||(o=a.from(o)),"des-ede"!==r&&"des-ede-cbc"!==r||(o=a.concat([o,o.slice(0,8)]));var c=e.iv;a.isBuffer(c)||(c=a.from(c)),this._des=i.create({key:o,iv:c,type:t})}s.des=s["des-cbc"],s.des3=s["des-ede3-cbc"],e.exports=c,o(c,n),c.prototype._update=function(e){return a.from(this._des.update(e))},c.prototype._final=function(){return a.from(this._des.final())}},99715:(e,t)=>{t["des-ecb"]={key:8,iv:0},t["des-cbc"]=t.des={key:8,iv:8},t["des-ede3-cbc"]=t.des3={key:24,iv:8},t["des-ede3"]={key:24,iv:0},t["des-ede-cbc"]={key:16,iv:8},t["des-ede"]={key:16,iv:0}},23663:(e,t,r)=>{var n=r(48764).Buffer,i=r(13550),o=r(61798);function a(e){var t,r=e.modulus.byteLength();do{t=new i(o(r))}while(t.cmp(e.modulus)>=0||!t.umod(e.prime1)||!t.umod(e.prime2));return t}function s(e,t){var r=function(e){var t=a(e);return{blinder:t.toRed(i.mont(e.modulus)).redPow(new i(e.publicExponent)).fromRed(),unblinder:t.invm(e.modulus)}}(t),o=t.modulus.byteLength(),s=new i(e).mul(r.blinder).umod(t.modulus),c=s.toRed(i.mont(t.prime1)),u=s.toRed(i.mont(t.prime2)),l=t.coefficient,d=t.prime1,f=t.prime2,h=c.redPow(t.exponent1).fromRed(),p=u.redPow(t.exponent2).fromRed(),g=h.isub(p).imul(l).umod(d).imul(f);return p.iadd(g).imul(r.unblinder).umod(t.modulus).toArrayLike(n,"be",o)}s.getr=a,e.exports=s},56042:(e,t,r)=>{e.exports=r(75207)},64743:(e,t,r)=>{var n=r(89509).Buffer,i=r(23482),o=r(88473),a=r(35717),s=r(82957),c=r(47753),u=r(75207);function l(e){o.Writable.call(this);var t=u[e];if(!t)throw new Error("Unknown message digest");this._hashType=t.hash,this._hash=i(t.hash),this._tag=t.id,this._signType=t.sign}function d(e){o.Writable.call(this);var t=u[e];if(!t)throw new Error("Unknown message digest");this._hash=i(t.hash),this._tag=t.id,this._signType=t.sign}function f(e){return new l(e)}function h(e){return new d(e)}Object.keys(u).forEach((function(e){u[e].id=n.from(u[e].id,"hex"),u[e.toLowerCase()]=u[e]})),a(l,o.Writable),l.prototype._write=function(e,t,r){this._hash.update(e),r()},l.prototype.update=function(e,t){return"string"==typeof e&&(e=n.from(e,t)),this._hash.update(e),this},l.prototype.sign=function(e,t){this.end();var r=this._hash.digest(),n=s(r,e,this._hashType,this._signType,this._tag);return t?n.toString(t):n},a(d,o.Writable),d.prototype._write=function(e,t,r){this._hash.update(e),r()},d.prototype.update=function(e,t){return"string"==typeof e&&(e=n.from(e,t)),this._hash.update(e),this},d.prototype.verify=function(e,t,r){"string"==typeof t&&(t=n.from(t,r)),this.end();var i=this._hash.digest();return c(t,i,e,this._signType,this._tag)},e.exports={Sign:f,Verify:h,createSign:f,createVerify:h}},82957:(e,t,r)=>{var n=r(89509).Buffer,i=r(58355),o=r(23663),a=r(86266).ec,s=r(13550),c=r(70980),u=r(1308);function l(e,t,r,o){if((e=n.from(e.toArray())).length0&&r.ishrn(n),r}function f(e,t,r){var o,a;do{for(o=n.alloc(0);8*o.length{var n=r(89509).Buffer,i=r(13550),o=r(86266).ec,a=r(70980),s=r(1308);function c(e,t){if(e.cmpn(0)<=0)throw new Error("invalid sig");if(e.cmp(t)>=t)throw new Error("invalid sig")}e.exports=function(e,t,r,u,l){var d=a(r);if("ec"===d.type){if("ecdsa"!==u&&"ecdsa/rsa"!==u)throw new Error("wrong public key type");return function(e,t,r){var n=s[r.data.algorithm.curve.join(".")];if(!n)throw new Error("unknown curve "+r.data.algorithm.curve.join("."));var i=new o(n),a=r.data.subjectPrivateKey.data;return i.verify(t,e,a)}(e,t,d)}if("dsa"===d.type){if("dsa"!==u)throw new Error("wrong public key type");return function(e,t,r){var n=r.data.p,o=r.data.q,s=r.data.g,u=r.data.pub_key,l=a.signature.decode(e,"der"),d=l.s,f=l.r;c(d,o),c(f,o);var h=i.mont(n),p=d.invm(o);return 0===s.toRed(h).redPow(new i(t).mul(p).mod(o)).fromRed().mul(u.toRed(h).redPow(f.mul(p).mod(o)).fromRed()).mod(n).mod(o).cmp(f)}(e,t,d)}if("rsa"!==u&&"ecdsa/rsa"!==u)throw new Error("wrong public key type");t=n.concat([l,t]);for(var f=d.modulus.byteLength(),h=[1],p=0;t.length+h.length+2{const n=r(58162);e.exports=n("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},53310:(e,t,r)=>{"use strict";var n=r(91518),i=r(89509).Buffer;e.exports=function(e){function t(t){var r=t.slice(0,-4),n=t.slice(-4),i=e(r);if(!(n[0]^i[0]|n[1]^i[1]|n[2]^i[2]|n[3]^i[3]))return r}return{encode:function(t){var r=e(t);return n.encode(i.concat([t,r],t.length+4))},decode:function(e){var r=t(n.decode(e));if(!r)throw new Error("Invalid checksum");return r},decodeUnsafe:function(e){var r=n.decodeUnsafe(e);if(r)return t(r)}}}},58334:(e,t,r)=>{"use strict";var n=r(23482),i=r(53310);e.exports=i((function(e){var t=n("sha256").update(e).digest();return n("sha256").update(t).digest()}))},32179:(e,t,r)=>{"use strict";var n=r(89509).Buffer;e.exports=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r>>0,l=new Uint8Array(a);e[r];){var d=t[e.charCodeAt(r)];if(255===d)return;for(var f=0,h=a-1;(0!==d||f>>0,l[h]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");o=f,r++}for(var p=a-o;p!==a&&0===l[p];)p++;var g=n.allocUnsafe(i+(a-p));g.fill(0,0,i);for(var m=i;p!==a;)g[m++]=l[p++];return g}return{encode:function(t){if((Array.isArray(t)||t instanceof Uint8Array)&&(t=n.from(t)),!n.isBuffer(t))throw new TypeError("Expected Buffer");if(0===t.length)return"";for(var r=0,i=0,o=0,a=t.length;o!==a&&0===t[o];)o++,r++;for(var u=(a-o)*l+1>>>0,d=new Uint8Array(u);o!==a;){for(var f=t[o],h=0,p=u-1;(0!==f||h>>0,d[p]=f%s>>>0,f=f/s>>>0;if(0!==f)throw new Error("Non-zero carry");i=h,o++}for(var g=u-i;g!==u&&0===d[g];)g++;for(var m=c.repeat(r);g{var n=r(32179);e.exports=n("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},67295:(e,t,r)=>{var n=r(48764).Buffer;e.exports=function(e,t){for(var r=Math.min(e.length,t.length),i=new n(r),o=0;o{"use strict";var n=r(25108);const i=r(79742),o=r(80645),a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=u,t.SlowBuffer=function(e){return+e!=e&&(e=0),u.alloc(+e)},t.INSPECT_MAX_BYTES=50;const s=2147483647;function c(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,u.prototype),t}function u(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return f(e)}return l(e,t,r)}function l(e,t,r){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!u.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|m(e,t);let n=c(r);const i=n.write(e,t);return i!==r&&(n=n.slice(0,i)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(Y(e,Uint8Array)){const t=new Uint8Array(e);return p(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Y(e,ArrayBuffer)||e&&Y(e.buffer,ArrayBuffer))return p(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(Y(e,SharedArrayBuffer)||e&&Y(e.buffer,SharedArrayBuffer)))return p(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return u.from(n,t,r);const i=function(e){if(u.isBuffer(e)){const t=0|g(e.length),r=c(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||Q(e.length)?c(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return u.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function d(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function f(e){return d(e),c(e<0?0:0|g(e))}function h(e){const t=e.length<0?0:0|g(e.length),r=c(t);for(let n=0;n=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function m(e,t){if(u.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Y(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(i)return n?-1:z(e).length;t=(""+t).toLowerCase(),i=!0}}function y(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return C(this,t,r);case"utf8":case"utf-8":return x(this,t,r);case"ascii":return k(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return I(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function b(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function v(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Q(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:w(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):w(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function w(e,t,r,n,i){let o,a=1,s=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,c/=2,r/=2}function u(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){let n=-1;for(o=r;os&&(r=s-c),o=r;o>=0;o--){let r=!0;for(let n=0;ni&&(n=i):n=i;const o=t.length;let a;for(n>o/2&&(n=o/2),a=0;a>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function I(e,t,r){return 0===t&&r===e.length?i.fromByteArray(e):i.fromByteArray(e.slice(t,r))}function x(e,t,r){r=Math.min(e.length,r);const n=[];let i=t;for(;i239?4:t>223?3:t>191?2:1;if(i+a<=r){let r,n,s,c;switch(a){case 1:t<128&&(o=t);break;case 2:r=e[i+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(o=c));break;case 3:r=e[i+1],n=e[i+2],128==(192&r)&&128==(192&n)&&(c=(15&t)<<12|(63&r)<<6|63&n,c>2047&&(c<55296||c>57343)&&(o=c));break;case 4:r=e[i+1],n=e[i+2],s=e[i+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(c=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,c>65535&&c<1114112&&(o=c))}}null===o?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=a}return function(e){const t=e.length;if(t<=O)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(u.isBuffer(t)||(t=u.from(t)),t.copy(n,i)):Uint8Array.prototype.set.call(n,t,i);else{if(!u.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,i)}i+=t.length}return n},u.byteLength=m,u.prototype._isBuffer=!0,u.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(e+=" ... "),""},a&&(u.prototype[a]=u.prototype.inspect),u.prototype.compare=function(e,t,r,n,i){if(Y(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;let o=(i>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0);const s=Math.min(o,a),c=this.slice(n,i),l=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return _(this,e,t,r);case"utf8":case"utf-8":return E(this,e,t,r);case"ascii":case"latin1":case"binary":return S(this,e,t,r);case"base64":return T(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const O=4096;function k(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;in)&&(r=n);let i="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function R(e,t,r,n,i,o){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function D(e,t,r,n,i){V(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function L(e,t,r,n,i){V(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r+7]=o,o>>=8,e[r+6]=o,o>>=8,e[r+5]=o,o>>=8,e[r+4]=o;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function B(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,r,n,i){return t=+t,r>>>=0,i||B(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function j(e,t,r,n,i){return t=+t,r>>>=0,i||B(e,0,r,8),o.write(e,t,r,n,52,8),r+8}u.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||M(e,t,this.length);let n=this[e],i=1,o=0;for(;++o>>=0,t>>>=0,r||M(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n},u.prototype.readUint8=u.prototype.readUInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=Z((function(e){$(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||K(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,i=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(i)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||K(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||M(e,t,this.length);let n=this[e],i=1,o=0;for(;++o=i&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||M(e,t,this.length);let n=t,i=1,o=this[e+--n];for(;n>0&&(i*=256);)o+=this[e+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},u.prototype.readInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||M(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){e>>>=0,t||M(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=Z((function(e){$(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||K(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||K(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||M(e,4,this.length),o.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||M(e,4,this.length),o.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||M(e,8,this.length),o.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||M(e,8,this.length),o.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||R(this,e,t,r,Math.pow(2,8*r)-1,0);let i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,n||R(this,e,t,r,Math.pow(2,8*r)-1,0);let i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigUInt64LE=Z((function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeBigUInt64BE=Z((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);R(this,e,t,r,n-1,-n)}let i=0,o=1,a=0;for(this[t]=255&e;++i>0)-a&255;return t+r},u.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);R(this,e,t,r,n-1,-n)}let i=r-1,o=1,a=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/o>>0)-a&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||R(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigInt64LE=Z((function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeBigInt64BE=Z((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return j(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return j(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function V(e,t,r,n,i,o){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new F.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){$(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||K(t,e.length-(r+1))}(n,i,o)}function $(e,t){if("number"!=typeof e)throw new F.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,r){if(Math.floor(e)!==e)throw $(e,r),new F.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new F.ERR_BUFFER_OUT_OF_BOUNDS;throw new F.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}H("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),H("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),H("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=W(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=W(i)),i+="n"),n+=` It must be ${t}. Received ${i}`,n}),RangeError);const q=/[^+/0-9A-Za-z-_]/g;function z(e,t){let r;t=t||1/0;const n=e.length;let i=null;const o=[];for(let a=0;a55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function G(e){return i.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(q,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function X(e,t,r,n){let i;for(i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function Y(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Q(e){return e!=e}const J=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)t[n+i]=e[r]+e[i]}return t}();function Z(e){return"undefined"==typeof BigInt?ee:e}function ee(){throw new Error("BigInt not supported")}},21924:(e,t,r)=>{"use strict";var n=r(40210),i=r(55559),o=i(n("String.prototype.indexOf"));e.exports=function(e,t){var r=n(e,!!t);return"function"==typeof r&&o(e,".prototype.")>-1?i(r):r}},55559:(e,t,r)=>{"use strict";var n=r(58612),i=r(40210),o=i("%Function.prototype.apply%"),a=i("%Function.prototype.call%"),s=i("%Reflect.apply%",!0)||n.call(a,o),c=i("%Object.getOwnPropertyDescriptor%",!0),u=i("%Object.defineProperty%",!0),l=i("%Math.max%");if(u)try{u({},"a",{value:1})}catch(e){u=null}e.exports=function(e){var t=s(n,a,arguments);if(c&&u){var r=c(t,"length");r.configurable&&u(t,"length",{value:1+l(0,e.length-(arguments.length-1))})}return t};var d=function(){return s(n,o,arguments)};u?u(e.exports,"apply",{value:d}):e.exports.apply=d},71027:(e,t,r)=>{var n=r(89509).Buffer,i=r(42830).Transform,o=r(32553).s;function a(e){i.call(this),this.hashMode="string"==typeof e,this.hashMode?this[e]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}r(35717)(a,i),a.prototype.update=function(e,t,r){"string"==typeof e&&(e=n.from(e,t));var i=this._update(e);return this.hashMode?this:(r&&(i=this._toString(i,r)),i)},a.prototype.setAutoPadding=function(){},a.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},a.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},a.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},a.prototype._transform=function(e,t,r){var n;try{this.hashMode?this._update(e):this.push(this._update(e))}catch(e){n=e}finally{r(n)}},a.prototype._flush=function(e){var t;try{this.push(this.__final())}catch(e){t=e}e(t)},a.prototype._finalOrDigest=function(e){var t=this.__final()||n.alloc(0);return e&&(t=this._toString(t,e,!0)),t},a.prototype._toString=function(e,t,r){if(this._decoder||(this._decoder=new o(t),this._encoding=t),this._encoding!==t)throw new Error("can't switch encodings");var n=this._decoder.write(e);return r&&(n+=this._decoder.end()),n},e.exports=a},25108:(e,t,r)=>{var n=r(89539),i=r(69282);function o(){return(new Date).getTime()}var a,s=Array.prototype.slice,c={};a=void 0!==r.g&&r.g.console?r.g.console:"undefined"!=typeof window&&window.console?window.console:{};for(var u=[[function(){},"log"],[function(){a.log.apply(a,arguments)},"info"],[function(){a.log.apply(a,arguments)},"warn"],[function(){a.warn.apply(a,arguments)},"error"],[function(e){c[e]=o()},"time"],[function(e){var t=c[e];if(!t)throw new Error("No such label: "+e);delete c[e];var r=o()-t;a.log(e+": "+r+"ms")},"timeEnd"],[function(){var e=new Error;e.name="Trace",e.message=n.format.apply(null,arguments),a.error(e.stack)},"trace"],[function(e){a.log(n.inspect(e)+"\n")},"dir"],[function(e){if(!e){var t=s.call(arguments,1);i.ok(!1,n.format.apply(null,t))}},"assert"]],l=0;l{var n=r(48764).Buffer,i=r(86266),o=r(13550);e.exports=function(e){return new s(e)};var a={secp256k1:{name:"secp256k1",byteLength:32},secp224r1:{name:"p224",byteLength:28},prime256v1:{name:"p256",byteLength:32},prime192v1:{name:"p192",byteLength:24},ed25519:{name:"ed25519",byteLength:32},secp384r1:{name:"p384",byteLength:48},secp521r1:{name:"p521",byteLength:66}};function s(e){this.curveType=a[e],this.curveType||(this.curveType={name:e}),this.curve=new i.ec(this.curveType.name),this.keys=void 0}function c(e,t,r){Array.isArray(e)||(e=e.toArray());var i=new n(e);if(r&&i.length{"use strict";var n=r(35717),i=r(62318),o=r(79785),a=r(89072),s=r(71027);function c(e){s.call(this,"digest"),this._hash=e}n(c,s),c.prototype._update=function(e){this._hash.update(e)},c.prototype._final=function(){return this._hash.digest()},e.exports=function(e){return"md5"===(e=e.toLowerCase())?new i:"rmd160"===e||"ripemd160"===e?new o:new c(a(e))}},78028:(e,t,r)=>{var n=r(62318);e.exports=function(e){return(new n).update(e).digest()}},58355:(e,t,r)=>{"use strict";var n=r(35717),i=r(51031),o=r(71027),a=r(89509).Buffer,s=r(78028),c=r(79785),u=r(89072),l=a.alloc(128);function d(e,t){o.call(this,"digest"),"string"==typeof t&&(t=a.from(t));var r="sha512"===e||"sha384"===e?128:64;this._alg=e,this._key=t,t.length>r?t=("rmd160"===e?new c:u(e)).update(t).digest():t.length{"use strict";var n=r(35717),i=r(89509).Buffer,o=r(71027),a=i.alloc(128),s=64;function c(e,t){o.call(this,"digest"),"string"==typeof t&&(t=i.from(t)),this._alg=e,this._key=t,t.length>s?t=e(t):t.length{var n=r(48764).Buffer;const i=r(60677),o=r(58334),{sha256:a,ripemd160:s}=r(33715),c=76067358,u=({networkVersion:e=c,depth:t,childNumber:r,chainCode:u,publicKey:l})=>{i(e,i.number.label("networkVersion")),i(t,i.number.label("depth")),i(r,i.number.label("childNumber")),i(u,i.string.label("chainCode")),i(l,i.string.label("publicKey"));const d=(e=>{const t=(r=e=n.from(e,"hex"),s().update(a().update(r).digest()).digest());var r;return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0})(l=(e=>e.startsWith("02")||e.startsWith("03")?e:(parseInt(e.slice(-2),16)%2==0?"02":"03")+e.slice(2,66))(l)),f=n.from([e.toString(16).padStart(8,"0"),t.toString(16).padStart(2,"0"),d.toString(16).padStart(8,"0"),r.toString(16).padStart(8,"0"),u,l].join(""),"hex");return o.encode(f)};u.mainnet=c,u.testnet=70617039,e.exports=u},55835:(e,t,r)=>{"use strict";t.randomBytes=t.rng=t.pseudoRandomBytes=t.prng=r(61798),t.createHash=t.Hash=r(23482),t.createHmac=t.Hmac=r(58355);var n=r(56042),i=Object.keys(n),o=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(i);t.getHashes=function(){return o};var a=r(25632);t.pbkdf2=a.pbkdf2,t.pbkdf2Sync=a.pbkdf2Sync;var s=r(53614);t.Cipher=s.Cipher,t.createCipher=s.createCipher,t.Cipheriv=s.Cipheriv,t.createCipheriv=s.createCipheriv,t.Decipher=s.Decipher,t.createDecipher=s.createDecipher,t.Decipheriv=s.Decipheriv,t.createDecipheriv=s.createDecipheriv,t.getCiphers=s.getCiphers,t.listCiphers=s.listCiphers;var c=r(62607);t.DiffieHellmanGroup=c.DiffieHellmanGroup,t.createDiffieHellmanGroup=c.createDiffieHellmanGroup,t.getDiffieHellman=c.getDiffieHellman,t.createDiffieHellman=c.createDiffieHellman,t.DiffieHellman=c.DiffieHellman;var u=r(64743);t.createSign=u.createSign,t.Sign=u.Sign,t.createVerify=u.createVerify,t.Verify=u.Verify,t.createECDH=r(76393);var l=r(7900);t.publicEncrypt=l.publicEncrypt,t.privateEncrypt=l.privateEncrypt,t.publicDecrypt=l.publicDecrypt,t.privateDecrypt=l.privateDecrypt;var d=r(77963);t.randomFill=d.randomFill,t.randomFillSync=d.randomFillSync,t.createCredentials=function(){throw new Error(["sorry, createCredentials is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join("\n"))},t.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}},4289:(e,t,r)=>{"use strict";var n=r(82215),i="function"==typeof Symbol&&"symbol"==typeof Symbol("foo"),o=Object.prototype.toString,a=Array.prototype.concat,s=Object.defineProperty,c=r(31044)(),u=s&&c,l=function(e,t,r,n){var i;(!(t in e)||"function"==typeof(i=n)&&"[object Function]"===o.call(i)&&n())&&(u?s(e,t,{configurable:!0,enumerable:!1,value:r,writable:!0}):e[t]=r)},d=function(e,t){var r=arguments.length>2?arguments[2]:{},o=n(t);i&&(o=a.call(o,Object.getOwnPropertySymbols(t)));for(var s=0;s{"use strict";t.utils=r(11278),t.Cipher=r(55756),t.DES=r(70778),t.CBC=r(39051),t.EDE=r(50651)},39051:(e,t,r)=>{"use strict";var n=r(79746),i=r(35717),o={};function a(e){n.equal(e.length,8,"Invalid IV length"),this.iv=new Array(8);for(var t=0;t{"use strict";var n=r(79746);function i(e){this.options=e,this.type=this.options.type,this.blockSize=8,this._init(),this.buffer=new Array(this.blockSize),this.bufferOff=0}e.exports=i,i.prototype._init=function(){},i.prototype.update=function(e){return 0===e.length?[]:"decrypt"===this.type?this._updateDecrypt(e):this._updateEncrypt(e)},i.prototype._buffer=function(e,t){for(var r=Math.min(this.buffer.length-this.bufferOff,e.length-t),n=0;n0;n--)t+=this._buffer(e,t),r+=this._flushBuffer(i,r);return t+=this._buffer(e,t),i},i.prototype.final=function(e){var t,r;return e&&(t=this.update(e)),r="encrypt"===this.type?this._finalEncrypt():this._finalDecrypt(),t?t.concat(r):r},i.prototype._pad=function(e,t){if(0===t)return!1;for(;t{"use strict";var n=r(79746),i=r(35717),o=r(11278),a=r(55756);function s(){this.tmp=new Array(2),this.keys=null}function c(e){a.call(this,e);var t=new s;this._desState=t,this.deriveKeys(t,e.key)}i(c,a),e.exports=c,c.create=function(e){return new c(e)};var u=[1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1];c.prototype.deriveKeys=function(e,t){e.keys=new Array(32),n.equal(t.length,this.blockSize,"Invalid key length");var r=o.readUInt32BE(t,0),i=o.readUInt32BE(t,4);o.pc1(r,i,e.tmp,0),r=e.tmp[0],i=e.tmp[1];for(var a=0;a>>1];r=o.r28shl(r,s),i=o.r28shl(i,s),o.pc2(r,i,e.keys,a)}},c.prototype._update=function(e,t,r,n){var i=this._desState,a=o.readUInt32BE(e,t),s=o.readUInt32BE(e,t+4);o.ip(a,s,i.tmp,0),a=i.tmp[0],s=i.tmp[1],"encrypt"===this.type?this._encrypt(i,a,s,i.tmp,0):this._decrypt(i,a,s,i.tmp,0),a=i.tmp[0],s=i.tmp[1],o.writeUInt32BE(r,a,n),o.writeUInt32BE(r,s,n+4)},c.prototype._pad=function(e,t){for(var r=e.length-t,n=t;n>>0,a=f}o.rip(s,a,n,i)},c.prototype._decrypt=function(e,t,r,n,i){for(var a=r,s=t,c=e.keys.length-2;c>=0;c-=2){var u=e.keys[c],l=e.keys[c+1];o.expand(a,e.tmp,0),u^=e.tmp[0],l^=e.tmp[1];var d=o.substitute(u,l),f=a;a=(s^o.permute(d))>>>0,s=f}o.rip(a,s,n,i)}},50651:(e,t,r)=>{"use strict";var n=r(79746),i=r(35717),o=r(55756),a=r(70778);function s(e,t){n.equal(t.length,24,"Invalid key length");var r=t.slice(0,8),i=t.slice(8,16),o=t.slice(16,24);this.ciphers="encrypt"===e?[a.create({type:"encrypt",key:r}),a.create({type:"decrypt",key:i}),a.create({type:"encrypt",key:o})]:[a.create({type:"decrypt",key:o}),a.create({type:"encrypt",key:i}),a.create({type:"decrypt",key:r})]}function c(e){o.call(this,e);var t=new s(this.type,this.options.key);this._edeState=t}i(c,o),e.exports=c,c.create=function(e){return new c(e)},c.prototype._update=function(e,t,r,n){var i=this._edeState;i.ciphers[0]._update(e,t,r,n),i.ciphers[1]._update(r,n,r,n),i.ciphers[2]._update(r,n,r,n)},c.prototype._pad=a.prototype._pad,c.prototype._unpad=a.prototype._unpad},11278:(e,t)=>{"use strict";t.readUInt32BE=function(e,t){return(e[0+t]<<24|e[1+t]<<16|e[2+t]<<8|e[3+t])>>>0},t.writeUInt32BE=function(e,t,r){e[0+r]=t>>>24,e[1+r]=t>>>16&255,e[2+r]=t>>>8&255,e[3+r]=255&t},t.ip=function(e,t,r,n){for(var i=0,o=0,a=6;a>=0;a-=2){for(var s=0;s<=24;s+=8)i<<=1,i|=t>>>s+a&1;for(s=0;s<=24;s+=8)i<<=1,i|=e>>>s+a&1}for(a=6;a>=0;a-=2){for(s=1;s<=25;s+=8)o<<=1,o|=t>>>s+a&1;for(s=1;s<=25;s+=8)o<<=1,o|=e>>>s+a&1}r[n+0]=i>>>0,r[n+1]=o>>>0},t.rip=function(e,t,r,n){for(var i=0,o=0,a=0;a<4;a++)for(var s=24;s>=0;s-=8)i<<=1,i|=t>>>s+a&1,i<<=1,i|=e>>>s+a&1;for(a=4;a<8;a++)for(s=24;s>=0;s-=8)o<<=1,o|=t>>>s+a&1,o<<=1,o|=e>>>s+a&1;r[n+0]=i>>>0,r[n+1]=o>>>0},t.pc1=function(e,t,r,n){for(var i=0,o=0,a=7;a>=5;a--){for(var s=0;s<=24;s+=8)i<<=1,i|=t>>s+a&1;for(s=0;s<=24;s+=8)i<<=1,i|=e>>s+a&1}for(s=0;s<=24;s+=8)i<<=1,i|=t>>s+a&1;for(a=1;a<=3;a++){for(s=0;s<=24;s+=8)o<<=1,o|=t>>s+a&1;for(s=0;s<=24;s+=8)o<<=1,o|=e>>s+a&1}for(s=0;s<=24;s+=8)o<<=1,o|=e>>s+a&1;r[n+0]=i>>>0,r[n+1]=o>>>0},t.r28shl=function(e,t){return e<>>28-t};var r=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];t.pc2=function(e,t,n,i){for(var o=0,a=0,s=r.length>>>1,c=0;c>>r[c]&1;for(c=s;c>>r[c]&1;n[i+0]=o>>>0,n[i+1]=a>>>0},t.expand=function(e,t,r){var n=0,i=0;n=(1&e)<<5|e>>>27;for(var o=23;o>=15;o-=4)n<<=6,n|=e>>>o&63;for(o=11;o>=3;o-=4)i|=e>>>o&63,i<<=6;i|=(31&e)<<1|e>>>31,t[r+0]=n>>>0,t[r+1]=i>>>0};var n=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];t.substitute=function(e,t){for(var r=0,i=0;i<4;i++)r<<=4,r|=n[64*i+(e>>>18-6*i&63)];for(i=0;i<4;i++)r<<=4,r|=n[256+64*i+(t>>>18-6*i&63)];return r>>>0};var i=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];t.permute=function(e){for(var t=0,r=0;r>>i[r]&1;return t>>>0},t.padSplit=function(e,t,r){for(var n=e.toString(2);n.length{var n=r(48764).Buffer,i=r(43590),o=r(29799),a=r(57426),s={binary:!0,hex:!0,base64:!0};t.DiffieHellmanGroup=t.createDiffieHellmanGroup=t.getDiffieHellman=function(e){var t=new n(o[e].prime,"hex"),r=new n(o[e].gen,"hex");return new a(t,r)},t.createDiffieHellman=t.DiffieHellman=function e(t,r,o,c){return n.isBuffer(r)||void 0===s[r]?e(t,"binary",r,o):(r=r||"binary",c=c||"binary",o=o||new n([2]),n.isBuffer(o)||(o=new n(o,c)),"number"==typeof t?new a(i(t,o),o,!0):(n.isBuffer(t)||(t=new n(t,r)),new a(t,o,!0)))}},57426:(e,t,r)=>{var n=r(48764).Buffer,i=r(13550),o=new(r(63047)),a=new i(24),s=new i(11),c=new i(10),u=new i(3),l=new i(7),d=r(43590),f=r(61798);function h(e,t){return t=t||"utf8",n.isBuffer(e)||(e=new n(e,t)),this._pub=new i(e),this}function p(e,t){return t=t||"utf8",n.isBuffer(e)||(e=new n(e,t)),this._priv=new i(e),this}e.exports=m;var g={};function m(e,t,r){this.setGenerator(t),this.__prime=new i(e),this._prime=i.mont(this.__prime),this._primeLen=e.length,this._pub=void 0,this._priv=void 0,this._primeCode=void 0,r?(this.setPublicKey=h,this.setPrivateKey=p):this._primeCode=8}function y(e,t){var r=new n(e.toArray());return t?r.toString(t):r}Object.defineProperty(m.prototype,"verifyError",{enumerable:!0,get:function(){return"number"!=typeof this._primeCode&&(this._primeCode=function(e,t){var r=t.toString("hex"),n=[r,e.toString(16)].join("_");if(n in g)return g[n];var i,f=0;if(e.isEven()||!d.simpleSieve||!d.fermatTest(e)||!o.test(e))return f+=1,f+="02"===r||"05"===r?8:4,g[n]=f,f;switch(o.test(e.shrn(1))||(f+=2),r){case"02":e.mod(a).cmp(s)&&(f+=8);break;case"05":(i=e.mod(c)).cmp(u)&&i.cmp(l)&&(f+=8);break;default:f+=4}return g[n]=f,f}(this.__prime,this.__gen)),this._primeCode}}),m.prototype.generateKeys=function(){return this._priv||(this._priv=new i(f(this._primeLen))),this._pub=this._gen.toRed(this._prime).redPow(this._priv).fromRed(),this.getPublicKey()},m.prototype.computeSecret=function(e){var t=(e=(e=new i(e)).toRed(this._prime)).redPow(this._priv).fromRed(),r=new n(t.toArray()),o=this.getPrime();if(r.length{var n=r(61798);e.exports=b,b.simpleSieve=m,b.fermatTest=y;var i=r(13550),o=new i(24),a=new(r(63047)),s=new i(1),c=new i(2),u=new i(5),l=(new i(16),new i(8),new i(10)),d=new i(3),f=(new i(7),new i(11)),h=new i(4),p=(new i(12),null);function g(){if(null!==p)return p;var e=[];e[0]=2;for(var t=1,r=3;r<1048576;r+=2){for(var n=Math.ceil(Math.sqrt(r)),i=0;ie;)r.ishrn(1);if(r.isEven()&&r.iadd(s),r.testn(1)||r.iadd(c),t.cmp(c)){if(!t.cmp(u))for(;r.mod(l).cmp(d);)r.iadd(h)}else for(;r.mod(o).cmp(f);)r.iadd(h);if(m(p=r.shrn(1))&&m(r)&&y(p)&&y(r)&&a.test(p)&&a.test(r))return r}}},86266:(e,t,r)=>{"use strict";var n=t;n.version=r(18597).i8,n.utils=r(80953),n.rand=r(29931),n.curve=r(88254),n.curves=r(45427),n.ec=r(57954),n.eddsa=r(65980)},4918:(e,t,r)=>{"use strict";var n=r(13550),i=r(80953),o=i.getNAF,a=i.getJSF,s=i.assert;function c(e,t){this.type=e,this.p=new n(t.p,16),this.red=t.prime?n.red(t.prime):n.mont(this.p),this.zero=new n(0).toRed(this.red),this.one=new n(1).toRed(this.red),this.two=new n(2).toRed(this.red),this.n=t.n&&new n(t.n,16),this.g=t.g&&this.pointFromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}function u(e,t){this.curve=e,this.type=t,this.precomputed=null}e.exports=c,c.prototype.point=function(){throw new Error("Not implemented")},c.prototype.validate=function(){throw new Error("Not implemented")},c.prototype._fixedNafMul=function(e,t){s(e.precomputed);var r=e._getDoubles(),n=o(t,1,this._bitLength),i=(1<=a;l--)c=(c<<1)+n[l];u.push(c)}for(var d=this.jpoint(null,null,null),f=this.jpoint(null,null,null),h=i;h>0;h--){for(a=0;a=0;u--){for(var l=0;u>=0&&0===a[u];u--)l++;if(u>=0&&l++,c=c.dblp(l),u<0)break;var d=a[u];s(0!==d),c="affine"===e.type?d>0?c.mixedAdd(i[d-1>>1]):c.mixedAdd(i[-d-1>>1].neg()):d>0?c.add(i[d-1>>1]):c.add(i[-d-1>>1].neg())}return"affine"===e.type?c.toP():c},c.prototype._wnafMulAdd=function(e,t,r,n,i){var s,c,u,l=this._wnafT1,d=this._wnafT2,f=this._wnafT3,h=0;for(s=0;s=1;s-=2){var g=s-1,m=s;if(1===l[g]&&1===l[m]){var y=[t[g],null,null,t[m]];0===t[g].y.cmp(t[m].y)?(y[1]=t[g].add(t[m]),y[2]=t[g].toJ().mixedAdd(t[m].neg())):0===t[g].y.cmp(t[m].y.redNeg())?(y[1]=t[g].toJ().mixedAdd(t[m]),y[2]=t[g].add(t[m].neg())):(y[1]=t[g].toJ().mixedAdd(t[m]),y[2]=t[g].toJ().mixedAdd(t[m].neg()));var b=[-3,-1,-5,-7,0,7,5,1,3],v=a(r[g],r[m]);for(h=Math.max(v[0].length,h),f[g]=new Array(h),f[m]=new Array(h),c=0;c=0;s--){for(var T=0;s>=0;){var A=!0;for(c=0;c=0&&T++,E=E.dblp(T),s<0)break;for(c=0;c0?u=d[c][I-1>>1]:I<0&&(u=d[c][-I-1>>1].neg()),E="affine"===u.type?E.mixedAdd(u):E.add(u))}}for(s=0;s=Math.ceil((e.bitLength()+1)/t.step)},u.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i{"use strict";var n=r(80953),i=r(13550),o=r(35717),a=r(4918),s=n.assert;function c(e){this.twisted=1!=(0|e.a),this.mOneA=this.twisted&&-1==(0|e.a),this.extended=this.mOneA,a.call(this,"edwards",e),this.a=new i(e.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new i(e.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new i(e.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),s(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|e.c)}function u(e,t,r,n,o){a.BasePoint.call(this,e,"projective"),null===t&&null===r&&null===n?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new i(t,16),this.y=new i(r,16),this.z=n?new i(n,16):this.curve.one,this.t=o&&new i(o,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}o(c,a),e.exports=c,c.prototype._mulA=function(e){return this.mOneA?e.redNeg():this.a.redMul(e)},c.prototype._mulC=function(e){return this.oneC?e:this.c.redMul(e)},c.prototype.jpoint=function(e,t,r,n){return this.point(e,t,r,n)},c.prototype.pointFromX=function(e,t){(e=new i(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr(),n=this.c2.redSub(this.a.redMul(r)),o=this.one.redSub(this.c2.redMul(this.d).redMul(r)),a=n.redMul(o.redInvm()),s=a.redSqrt();if(0!==s.redSqr().redSub(a).cmp(this.zero))throw new Error("invalid point");var c=s.fromRed().isOdd();return(t&&!c||!t&&c)&&(s=s.redNeg()),this.point(e,s)},c.prototype.pointFromY=function(e,t){(e=new i(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr(),n=r.redSub(this.c2),o=r.redMul(this.d).redMul(this.c2).redSub(this.a),a=n.redMul(o.redInvm());if(0===a.cmp(this.zero)){if(t)throw new Error("invalid point");return this.point(this.zero,e)}var s=a.redSqrt();if(0!==s.redSqr().redSub(a).cmp(this.zero))throw new Error("invalid point");return s.fromRed().isOdd()!==t&&(s=s.redNeg()),this.point(s,e)},c.prototype.validate=function(e){if(e.isInfinity())return!0;e.normalize();var t=e.x.redSqr(),r=e.y.redSqr(),n=t.redMul(this.a).redAdd(r),i=this.c2.redMul(this.one.redAdd(this.d.redMul(t).redMul(r)));return 0===n.cmp(i)},o(u,a.BasePoint),c.prototype.pointFromJSON=function(e){return u.fromJSON(this,e)},c.prototype.point=function(e,t,r,n){return new u(this,e,t,r,n)},u.fromJSON=function(e,t){return new u(e,t[0],t[1],t[2])},u.prototype.inspect=function(){return this.isInfinity()?"":""},u.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},u.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(e),i=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),o=n.redAdd(t),a=o.redSub(r),s=n.redSub(t),c=i.redMul(a),u=o.redMul(s),l=i.redMul(s),d=a.redMul(o);return this.curve.point(c,u,d,l)},u.prototype._projDbl=function(){var e,t,r,n,i,o,a=this.x.redAdd(this.y).redSqr(),s=this.x.redSqr(),c=this.y.redSqr();if(this.curve.twisted){var u=(n=this.curve._mulA(s)).redAdd(c);this.zOne?(e=a.redSub(s).redSub(c).redMul(u.redSub(this.curve.two)),t=u.redMul(n.redSub(c)),r=u.redSqr().redSub(u).redSub(u)):(i=this.z.redSqr(),o=u.redSub(i).redISub(i),e=a.redSub(s).redISub(c).redMul(o),t=u.redMul(n.redSub(c)),r=u.redMul(o))}else n=s.redAdd(c),i=this.curve._mulC(this.z).redSqr(),o=n.redSub(i).redSub(i),e=this.curve._mulC(a.redISub(n)).redMul(o),t=this.curve._mulC(n).redMul(s.redISub(c)),r=n.redMul(o);return this.curve.point(e,t,r)},u.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},u.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),r=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),n=this.t.redMul(this.curve.dd).redMul(e.t),i=this.z.redMul(e.z.redAdd(e.z)),o=r.redSub(t),a=i.redSub(n),s=i.redAdd(n),c=r.redAdd(t),u=o.redMul(a),l=s.redMul(c),d=o.redMul(c),f=a.redMul(s);return this.curve.point(u,l,f,d)},u.prototype._projAdd=function(e){var t,r,n=this.z.redMul(e.z),i=n.redSqr(),o=this.x.redMul(e.x),a=this.y.redMul(e.y),s=this.curve.d.redMul(o).redMul(a),c=i.redSub(s),u=i.redAdd(s),l=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(o).redISub(a),d=n.redMul(c).redMul(l);return this.curve.twisted?(t=n.redMul(u).redMul(a.redSub(this.curve._mulA(o))),r=c.redMul(u)):(t=n.redMul(u).redMul(a.redSub(o)),r=this.curve._mulC(c).redMul(u)),this.curve.point(d,t,r)},u.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},u.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},u.prototype.mulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!1)},u.prototype.jmulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!0)},u.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},u.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},u.prototype.getX=function(){return this.normalize(),this.x.fromRed()},u.prototype.getY=function(){return this.normalize(),this.y.fromRed()},u.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},u.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(t))return!0;for(var r=e.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(n),0===this.x.cmp(t))return!0}},u.prototype.toP=u.prototype.normalize,u.prototype.mixedAdd=u.prototype.add},88254:(e,t,r)=>{"use strict";var n=t;n.base=r(4918),n.short=r(6673),n.mont=r(22881),n.edwards=r(31138)},22881:(e,t,r)=>{"use strict";var n=r(13550),i=r(35717),o=r(4918),a=r(80953);function s(e){o.call(this,"mont",e),this.a=new n(e.a,16).toRed(this.red),this.b=new n(e.b,16).toRed(this.red),this.i4=new n(4).toRed(this.red).redInvm(),this.two=new n(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}function c(e,t,r){o.BasePoint.call(this,e,"projective"),null===t&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new n(t,16),this.z=new n(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}i(s,o),e.exports=s,s.prototype.validate=function(e){var t=e.normalize().x,r=t.redSqr(),n=r.redMul(t).redAdd(r.redMul(this.a)).redAdd(t);return 0===n.redSqrt().redSqr().cmp(n)},i(c,o.BasePoint),s.prototype.decodePoint=function(e,t){return this.point(a.toArray(e,t),1)},s.prototype.point=function(e,t){return new c(this,e,t)},s.prototype.pointFromJSON=function(e){return c.fromJSON(this,e)},c.prototype.precompute=function(){},c.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},c.fromJSON=function(e,t){return new c(e,t[0],t[1]||e.one)},c.prototype.inspect=function(){return this.isInfinity()?"":""},c.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},c.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),t=this.x.redSub(this.z).redSqr(),r=e.redSub(t),n=e.redMul(t),i=r.redMul(t.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},c.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.diffAdd=function(e,t){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=e.x.redAdd(e.z),o=e.x.redSub(e.z).redMul(r),a=i.redMul(n),s=t.z.redMul(o.redAdd(a).redSqr()),c=t.x.redMul(o.redISub(a).redSqr());return this.curve.point(s,c)},c.prototype.mul=function(e){for(var t=e.clone(),r=this,n=this.curve.point(null,null),i=[];0!==t.cmpn(0);t.iushrn(1))i.push(t.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},c.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},c.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},c.prototype.getX=function(){return this.normalize(),this.x.fromRed()}},6673:(e,t,r)=>{"use strict";var n=r(80953),i=r(13550),o=r(35717),a=r(4918),s=n.assert;function c(e){a.call(this,"short",e),this.a=new i(e.a,16).toRed(this.red),this.b=new i(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(e),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}function u(e,t,r,n){a.BasePoint.call(this,e,"affine"),null===t&&null===r?(this.x=null,this.y=null,this.inf=!0):(this.x=new i(t,16),this.y=new i(r,16),n&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function l(e,t,r,n){a.BasePoint.call(this,e,"jacobian"),null===t&&null===r&&null===n?(this.x=this.curve.one,this.y=this.curve.one,this.z=new i(0)):(this.x=new i(t,16),this.y=new i(r,16),this.z=new i(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}o(c,a),e.exports=c,c.prototype._getEndomorphism=function(e){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var t,r;if(e.beta)t=new i(e.beta,16).toRed(this.red);else{var n=this._getEndoRoots(this.p);t=(t=n[0].cmp(n[1])<0?n[0]:n[1]).toRed(this.red)}if(e.lambda)r=new i(e.lambda,16);else{var o=this._getEndoRoots(this.n);0===this.g.mul(o[0]).x.cmp(this.g.x.redMul(t))?r=o[0]:(r=o[1],s(0===this.g.mul(r).x.cmp(this.g.x.redMul(t))))}return{beta:t,lambda:r,basis:e.basis?e.basis.map((function(e){return{a:new i(e.a,16),b:new i(e.b,16)}})):this._getEndoBasis(r)}}},c.prototype._getEndoRoots=function(e){var t=e===this.p?this.red:i.mont(e),r=new i(2).toRed(t).redInvm(),n=r.redNeg(),o=new i(3).toRed(t).redNeg().redSqrt().redMul(r);return[n.redAdd(o).fromRed(),n.redSub(o).fromRed()]},c.prototype._getEndoBasis=function(e){for(var t,r,n,o,a,s,c,u,l,d=this.n.ushrn(Math.floor(this.n.bitLength()/2)),f=e,h=this.n.clone(),p=new i(1),g=new i(0),m=new i(0),y=new i(1),b=0;0!==f.cmpn(0);){var v=h.div(f);u=h.sub(v.mul(f)),l=m.sub(v.mul(p));var w=y.sub(v.mul(g));if(!n&&u.cmp(d)<0)t=c.neg(),r=p,n=u.neg(),o=l;else if(n&&2==++b)break;c=u,h=f,f=u,m=p,p=l,y=g,g=w}a=u.neg(),s=l;var _=n.sqr().add(o.sqr());return a.sqr().add(s.sqr()).cmp(_)>=0&&(a=t,s=r),n.negative&&(n=n.neg(),o=o.neg()),a.negative&&(a=a.neg(),s=s.neg()),[{a:n,b:o},{a,b:s}]},c.prototype._endoSplit=function(e){var t=this.endo.basis,r=t[0],n=t[1],i=n.b.mul(e).divRound(this.n),o=r.b.neg().mul(e).divRound(this.n),a=i.mul(r.a),s=o.mul(n.a),c=i.mul(r.b),u=o.mul(n.b);return{k1:e.sub(a).sub(s),k2:c.add(u).neg()}},c.prototype.pointFromX=function(e,t){(e=new i(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var o=n.fromRed().isOdd();return(t&&!o||!t&&o)&&(n=n.redNeg()),this.point(e,n)},c.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,r=e.y,n=this.a.redMul(t),i=t.redSqr().redMul(t).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},c.prototype._endoWnafMulAdd=function(e,t,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},u.prototype.isInfinity=function(){return this.inf},u.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var r=t.redSqr().redISub(this.x).redISub(e.x),n=t.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},u.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,r=this.x.redSqr(),n=e.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),a=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,a)},u.prototype.getX=function(){return this.x.fromRed()},u.prototype.getY=function(){return this.y.fromRed()},u.prototype.mul=function(e){return e=new i(e,16),this.isInfinity()?this:this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},u.prototype.mulAdd=function(e,t,r){var n=[this,t],i=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},u.prototype.jmulAdd=function(e,t,r){var n=[this,t],i=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},u.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},u.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var r=this.precomputed,n=function(e){return e.neg()};t.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return t},u.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},o(l,a.BasePoint),c.prototype.jpoint=function(e,t,r){return new l(this,e,t,r)},l.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),n=this.y.redMul(t).redMul(e);return this.curve.point(r,n)},l.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},l.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(t),i=e.x.redMul(r),o=this.y.redMul(t.redMul(e.z)),a=e.y.redMul(r.redMul(this.z)),s=n.redSub(i),c=o.redSub(a);if(0===s.cmpn(0))return 0!==c.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var u=s.redSqr(),l=u.redMul(s),d=n.redMul(u),f=c.redSqr().redIAdd(l).redISub(d).redISub(d),h=c.redMul(d.redISub(f)).redISub(o.redMul(l)),p=this.z.redMul(e.z).redMul(s);return this.curve.jpoint(f,h,p)},l.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),r=this.x,n=e.x.redMul(t),i=this.y,o=e.y.redMul(t).redMul(this.z),a=r.redSub(n),s=i.redSub(o);if(0===a.cmpn(0))return 0!==s.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=a.redSqr(),u=c.redMul(a),l=r.redMul(c),d=s.redSqr().redIAdd(u).redISub(l).redISub(l),f=s.redMul(l.redISub(d)).redISub(i.redMul(u)),h=this.z.redMul(a);return this.curve.jpoint(d,f,h)},l.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();var t;if(this.curve.zeroA||this.curve.threeA){var r=this;for(t=0;t=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},l.prototype.inspect=function(){return this.isInfinity()?"":""},l.prototype.isInfinity=function(){return 0===this.z.cmpn(0)}},45427:(e,t,r)=>{"use strict";var n,i=t,o=r(33715),a=r(88254),s=r(80953).assert;function c(e){"short"===e.type?this.curve=new a.short(e):"edwards"===e.type?this.curve=new a.edwards(e):this.curve=new a.mont(e),this.g=this.curve.g,this.n=this.curve.n,this.hash=e.hash,s(this.g.validate(),"Invalid curve"),s(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function u(e,t){Object.defineProperty(i,e,{configurable:!0,enumerable:!0,get:function(){var r=new c(t);return Object.defineProperty(i,e,{configurable:!0,enumerable:!0,value:r}),r}})}i.PresetCurve=c,u("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:o.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),u("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:o.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),u("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:o.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),u("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:o.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),u("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:o.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),u("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["9"]}),u("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{n=r(91037)}catch(e){n=void 0}u("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:o.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",n]})},57954:(e,t,r)=>{"use strict";var n=r(13550),i=r(2156),o=r(80953),a=r(45427),s=r(29931),c=o.assert,u=r(31251),l=r(90611);function d(e){if(!(this instanceof d))return new d(e);"string"==typeof e&&(c(Object.prototype.hasOwnProperty.call(a,e),"Unknown curve "+e),e=a[e]),e instanceof a.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}e.exports=d,d.prototype.keyPair=function(e){return new u(this,e)},d.prototype.keyFromPrivate=function(e,t){return u.fromPrivate(this,e,t)},d.prototype.keyFromPublic=function(e,t){return u.fromPublic(this,e,t)},d.prototype.genKeyPair=function(e){e||(e={});for(var t=new i({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||s(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),o=this.n.sub(new n(2));;){var a=new n(t.generate(r));if(!(a.cmp(o)>0))return a.iaddn(1),this.keyFromPrivate(a)}},d.prototype._truncateToN=function(e,t){var r=8*e.byteLength()-this.n.bitLength();return r>0&&(e=e.ushrn(r)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},d.prototype.sign=function(e,t,r,o){"object"==typeof r&&(o=r,r=null),o||(o={}),t=this.keyFromPrivate(t,r),e=this._truncateToN(new n(e,16));for(var a=this.n.byteLength(),s=t.getPrivate().toArray("be",a),c=e.toArray("be",a),u=new i({hash:this.hash,entropy:s,nonce:c,pers:o.pers,persEnc:o.persEnc||"utf8"}),d=this.n.sub(new n(1)),f=0;;f++){var h=o.k?o.k(f):new n(u.generate(this.n.byteLength()));if(!((h=this._truncateToN(h,!0)).cmpn(1)<=0||h.cmp(d)>=0)){var p=this.g.mul(h);if(!p.isInfinity()){var g=p.getX(),m=g.umod(this.n);if(0!==m.cmpn(0)){var y=h.invm(this.n).mul(m.mul(t.getPrivate()).iadd(e));if(0!==(y=y.umod(this.n)).cmpn(0)){var b=(p.getY().isOdd()?1:0)|(0!==g.cmp(m)?2:0);return o.canonical&&y.cmp(this.nh)>0&&(y=this.n.sub(y),b^=1),new l({r:m,s:y,recoveryParam:b})}}}}}},d.prototype.verify=function(e,t,r,i){e=this._truncateToN(new n(e,16)),r=this.keyFromPublic(r,i);var o=(t=new l(t,"hex")).r,a=t.s;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;if(a.cmpn(1)<0||a.cmp(this.n)>=0)return!1;var s,c=a.invm(this.n),u=c.mul(e).umod(this.n),d=c.mul(o).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(u,r.getPublic(),d)).isInfinity()&&s.eqXToP(o):!(s=this.g.mulAdd(u,r.getPublic(),d)).isInfinity()&&0===s.getX().umod(this.n).cmp(o)},d.prototype.recoverPubKey=function(e,t,r,i){c((3&r)===r,"The recovery param is more than two bits"),t=new l(t,i);var o=this.n,a=new n(e),s=t.r,u=t.s,d=1&r,f=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&f)throw new Error("Unable to find sencond key candinate");s=f?this.curve.pointFromX(s.add(this.curve.n),d):this.curve.pointFromX(s,d);var h=t.r.invm(o),p=o.sub(a).mul(h).umod(o),g=u.mul(h).umod(o);return this.g.mulAdd(p,s,g)},d.prototype.getKeyRecoveryParam=function(e,t,r,n){if(null!==(t=new l(t,n)).recoveryParam)return t.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(e,t,i)}catch(e){continue}if(o.eq(r))return i}throw new Error("Unable to find valid recovery factor")}},31251:(e,t,r)=>{"use strict";var n=r(13550),i=r(80953).assert;function o(e,t){this.ec=e,this.priv=null,this.pub=null,t.priv&&this._importPrivate(t.priv,t.privEnc),t.pub&&this._importPublic(t.pub,t.pubEnc)}e.exports=o,o.fromPublic=function(e,t,r){return t instanceof o?t:new o(e,{pub:t,pubEnc:r})},o.fromPrivate=function(e,t,r){return t instanceof o?t:new o(e,{priv:t,privEnc:r})},o.prototype.validate=function(){var e=this.getPublic();return e.isInfinity()?{result:!1,reason:"Invalid public key"}:e.validate()?e.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},o.prototype.getPublic=function(e,t){return"string"==typeof e&&(t=e,e=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),t?this.pub.encode(t,e):this.pub},o.prototype.getPrivate=function(e){return"hex"===e?this.priv.toString(16,2):this.priv},o.prototype._importPrivate=function(e,t){this.priv=new n(e,t||16),this.priv=this.priv.umod(this.ec.curve.n)},o.prototype._importPublic=function(e,t){if(e.x||e.y)return"mont"===this.ec.curve.type?i(e.x,"Need x coordinate"):"short"!==this.ec.curve.type&&"edwards"!==this.ec.curve.type||i(e.x&&e.y,"Need both x and y coordinate"),void(this.pub=this.ec.curve.point(e.x,e.y));this.pub=this.ec.curve.decodePoint(e,t)},o.prototype.derive=function(e){return e.validate()||i(e.validate(),"public point not validated"),e.mul(this.priv).getX()},o.prototype.sign=function(e,t,r){return this.ec.sign(e,this,t,r)},o.prototype.verify=function(e,t){return this.ec.verify(e,t,this)},o.prototype.inspect=function(){return""}},90611:(e,t,r)=>{"use strict";var n=r(13550),i=r(80953),o=i.assert;function a(e,t){if(e instanceof a)return e;this._importDER(e,t)||(o(e.r&&e.s,"Signature without r or s"),this.r=new n(e.r,16),this.s=new n(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}function s(){this.place=0}function c(e,t){var r=e[t.place++];if(!(128&r))return r;var n=15&r;if(0===n||n>4)return!1;for(var i=0,o=0,a=t.place;o>>=0;return!(i<=127)&&(t.place=a,i)}function u(e){for(var t=0,r=e.length-1;!e[t]&&!(128&e[t+1])&&t>>3);for(e.push(128|r);--r;)e.push(t>>>(r<<3)&255);e.push(t)}}e.exports=a,a.prototype._importDER=function(e,t){e=i.toArray(e,t);var r=new s;if(48!==e[r.place++])return!1;var o=c(e,r);if(!1===o)return!1;if(o+r.place!==e.length)return!1;if(2!==e[r.place++])return!1;var a=c(e,r);if(!1===a)return!1;var u=e.slice(r.place,a+r.place);if(r.place+=a,2!==e[r.place++])return!1;var l=c(e,r);if(!1===l)return!1;if(e.length!==l+r.place)return!1;var d=e.slice(r.place,l+r.place);if(0===u[0]){if(!(128&u[1]))return!1;u=u.slice(1)}if(0===d[0]){if(!(128&d[1]))return!1;d=d.slice(1)}return this.r=new n(u),this.s=new n(d),this.recoveryParam=null,!0},a.prototype.toDER=function(e){var t=this.r.toArray(),r=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&r[0]&&(r=[0].concat(r)),t=u(t),r=u(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];l(n,t.length),(n=n.concat(t)).push(2),l(n,r.length);var o=n.concat(r),a=[48];return l(a,o.length),a=a.concat(o),i.encode(a,e)}},65980:(e,t,r)=>{"use strict";var n=r(33715),i=r(45427),o=r(80953),a=o.assert,s=o.parseBytes,c=r(79087),u=r(23622);function l(e){if(a("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof l))return new l(e);e=i[e].curve,this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=n.sha512}e.exports=l,l.prototype.sign=function(e,t){e=s(e);var r=this.keyFromSecret(t),n=this.hashInt(r.messagePrefix(),e),i=this.g.mul(n),o=this.encodePoint(i),a=this.hashInt(o,r.pubBytes(),e).mul(r.priv()),c=n.add(a).umod(this.curve.n);return this.makeSignature({R:i,S:c,Rencoded:o})},l.prototype.verify=function(e,t,r){e=s(e),t=this.makeSignature(t);var n=this.keyFromPublic(r),i=this.hashInt(t.Rencoded(),n.pubBytes(),e),o=this.g.mul(t.S());return t.R().add(n.pub().mul(i)).eq(o)},l.prototype.hashInt=function(){for(var e=this.hash(),t=0;t{"use strict";var n=r(80953),i=n.assert,o=n.parseBytes,a=n.cachedProperty;function s(e,t){this.eddsa=e,this._secret=o(t.secret),e.isPoint(t.pub)?this._pub=t.pub:this._pubBytes=o(t.pub)}s.fromPublic=function(e,t){return t instanceof s?t:new s(e,{pub:t})},s.fromSecret=function(e,t){return t instanceof s?t:new s(e,{secret:t})},s.prototype.secret=function(){return this._secret},a(s,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),a(s,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),a(s,"privBytes",(function(){var e=this.eddsa,t=this.hash(),r=e.encodingLength-1,n=t.slice(0,e.encodingLength);return n[0]&=248,n[r]&=127,n[r]|=64,n})),a(s,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),a(s,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),a(s,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),s.prototype.sign=function(e){return i(this._secret,"KeyPair can only verify"),this.eddsa.sign(e,this)},s.prototype.verify=function(e,t){return this.eddsa.verify(e,t,this)},s.prototype.getSecret=function(e){return i(this._secret,"KeyPair is public only"),n.encode(this.secret(),e)},s.prototype.getPublic=function(e){return n.encode(this.pubBytes(),e)},e.exports=s},23622:(e,t,r)=>{"use strict";var n=r(13550),i=r(80953),o=i.assert,a=i.cachedProperty,s=i.parseBytes;function c(e,t){this.eddsa=e,"object"!=typeof t&&(t=s(t)),Array.isArray(t)&&(t={R:t.slice(0,e.encodingLength),S:t.slice(e.encodingLength)}),o(t.R&&t.S,"Signature without R or S"),e.isPoint(t.R)&&(this._R=t.R),t.S instanceof n&&(this._S=t.S),this._Rencoded=Array.isArray(t.R)?t.R:t.Rencoded,this._Sencoded=Array.isArray(t.S)?t.S:t.Sencoded}a(c,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),a(c,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),a(c,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),a(c,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),c.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},c.prototype.toHex=function(){return i.encode(this.toBytes(),"hex").toUpperCase()},e.exports=c},91037:e=>{e.exports={doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}},80953:(e,t,r)=>{"use strict";var n=t,i=r(13550),o=r(79746),a=r(34504);n.assert=o,n.toArray=a.toArray,n.zero2=a.zero2,n.toHex=a.toHex,n.encode=a.encode,n.getNAF=function(e,t,r){var n=new Array(Math.max(e.bitLength(),r)+1);n.fill(0);for(var i=1<(i>>1)-1?(i>>1)-c:c,o.isubn(s)):s=0,n[a]=s,o.iushrn(1)}return n},n.getJSF=function(e,t){var r=[[],[]];e=e.clone(),t=t.clone();for(var n,i=0,o=0;e.cmpn(-i)>0||t.cmpn(-o)>0;){var a,s,c=e.andln(3)+i&3,u=t.andln(3)+o&3;3===c&&(c=-1),3===u&&(u=-1),a=0==(1&c)?0:3!=(n=e.andln(7)+i&7)&&5!==n||2!==u?c:-c,r[0].push(a),s=0==(1&u)?0:3!=(n=t.andln(7)+o&7)&&5!==n||2!==c?u:-u,r[1].push(s),2*i===a+1&&(i=1-i),2*o===s+1&&(o=1-o),e.iushrn(1),t.iushrn(1)}return r},n.cachedProperty=function(e,t,r){var n="_"+t;e.prototype[t]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},n.parseBytes=function(e){return"string"==typeof e?n.toArray(e,"hex"):e},n.intFromLE=function(e){return new i(e,"hex","le")}},8091:e=>{"use strict";function t(e,t){if(null==e)throw new TypeError("Cannot convert first argument to object");for(var r=Object(e),n=1;n{"use strict";var n,i=r(25108),o="object"==typeof Reflect?Reflect:null,a=o&&"function"==typeof o.apply?o.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};n=o&&"function"==typeof o.ownKeys?o.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function c(){c.init.call(this)}e.exports=c,e.exports.once=function(e,t){return new Promise((function(r,n){function i(r){e.removeListener(t,o),n(r)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}b(e,t,o,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&b(e,"error",t,{once:!0})}(e,i)}))},c.EventEmitter=c,c.prototype._events=void 0,c.prototype._eventsCount=0,c.prototype._maxListeners=void 0;var u=10;function l(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function d(e){return void 0===e._maxListeners?c.defaultMaxListeners:e._maxListeners}function f(e,t,r,n){var o,a,s,c;if(l(r),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),a=e._events),s=a[t]),void 0===s)s=a[t]=r,++e._eventsCount;else if("function"==typeof s?s=a[t]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),(o=d(e))>0&&s.length>o&&!s.warned){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,c=u,i&&i.warn&&i.warn(c)}return e}function h(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=h.bind(n);return i.listener=r,n.wrapFn=i,i}function g(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(o=t[0]),o instanceof Error)throw o;var s=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw s.context=o,s}var c=i[e];if(void 0===c)return!1;if("function"==typeof c)a(c,this,t);else{var u=c.length,l=y(c,u);for(r=0;r=0;o--)if(r[o]===t||r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},c.prototype.listeners=function(e){return g(this,e,!0)},c.prototype.rawListeners=function(e){return g(this,e,!1)},c.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):m.call(e,t)},c.prototype.listenerCount=m,c.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},13048:(e,t,r)=>{var n=r(89509).Buffer,i=r(62318);e.exports=function(e,t,r,o){if(n.isBuffer(e)||(e=n.from(e,"binary")),t&&(n.isBuffer(t)||(t=n.from(t,"binary")),8!==t.length))throw new RangeError("salt should be Buffer with 8 byte length");for(var a=r/8,s=n.alloc(a),c=n.alloc(o||0),u=n.alloc(0);a>0||o>0;){var l=new i;l.update(u),l.update(e),t&&l.update(t),u=l.digest();var d=0;if(a>0){var f=s.length-a;d=Math.min(a,u.length),u.copy(s,f,0,d),a-=d}if(d0){var h=c.length-o,p=Math.min(o,u.length-d);u.copy(c,h,d,d+p),o-=p}}return u.fill(0),{key:s,iv:c}}},94029:(e,t,r)=>{"use strict";var n=r(95320),i=Object.prototype.toString,o=Object.prototype.hasOwnProperty,a=function(e,t,r){for(var n=0,i=e.length;n=3&&(o=r),"[object Array]"===i.call(e)?a(e,t,o):"string"==typeof e?s(e,t,o):c(e,t,o)}},17648:e=>{"use strict";var t="Function.prototype.bind called on incompatible ",r=Array.prototype.slice,n=Object.prototype.toString,i="[object Function]";e.exports=function(e){var o=this;if("function"!=typeof o||n.call(o)!==i)throw new TypeError(t+o);for(var a,s=r.call(arguments,1),c=function(){if(this instanceof a){var t=o.apply(this,s.concat(r.call(arguments)));return Object(t)===t?t:this}return o.apply(e,s.concat(r.call(arguments)))},u=Math.max(0,o.length-s.length),l=[],d=0;d{"use strict";var n=r(17648);e.exports=Function.prototype.bind||n},40210:(e,t,r)=>{"use strict";var n,i=SyntaxError,o=Function,a=TypeError,s=function(e){try{return o('"use strict"; return ('+e+").constructor;")()}catch(e){}},c=Object.getOwnPropertyDescriptor;if(c)try{c({},"")}catch(e){c=null}var u=function(){throw new a},l=c?function(){try{return u}catch(e){try{return c(arguments,"callee").get}catch(e){return u}}}():u,d=r(41405)(),f=Object.getPrototypeOf||function(e){return e.__proto__},h={},p="undefined"==typeof Uint8Array?n:f(Uint8Array),g={"%AggregateError%":"undefined"==typeof AggregateError?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?n:ArrayBuffer,"%ArrayIteratorPrototype%":d?f([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":h,"%AsyncGenerator%":h,"%AsyncGeneratorFunction%":h,"%AsyncIteratorPrototype%":h,"%Atomics%":"undefined"==typeof Atomics?n:Atomics,"%BigInt%":"undefined"==typeof BigInt?n:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?n:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?n:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?n:FinalizationRegistry,"%Function%":o,"%GeneratorFunction%":h,"%Int8Array%":"undefined"==typeof Int8Array?n:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?n:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":d?f(f([][Symbol.iterator]())):n,"%JSON%":"object"==typeof JSON?JSON:n,"%Map%":"undefined"==typeof Map?n:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&d?f((new Map)[Symbol.iterator]()):n,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?n:Promise,"%Proxy%":"undefined"==typeof Proxy?n:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?n:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?n:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&d?f((new Set)[Symbol.iterator]()):n,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":d?f(""[Symbol.iterator]()):n,"%Symbol%":d?Symbol:n,"%SyntaxError%":i,"%ThrowTypeError%":l,"%TypedArray%":p,"%TypeError%":a,"%Uint8Array%":"undefined"==typeof Uint8Array?n:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?n:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?n:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?n:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?n:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?n:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?n:WeakSet},m=function e(t){var r;if("%AsyncFunction%"===t)r=s("async function () {}");else if("%GeneratorFunction%"===t)r=s("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=s("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&(r=f(i.prototype))}return g[t]=r,r},y={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},b=r(58612),v=r(17642),w=b.call(Function.call,Array.prototype.concat),_=b.call(Function.apply,Array.prototype.splice),E=b.call(Function.call,String.prototype.replace),S=b.call(Function.call,String.prototype.slice),T=b.call(Function.call,RegExp.prototype.exec),A=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,I=/\\(\\)?/g,x=function(e){var t=S(e,0,1),r=S(e,-1);if("%"===t&&"%"!==r)throw new i("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new i("invalid intrinsic syntax, expected opening `%`");var n=[];return E(e,A,(function(e,t,r,i){n[n.length]=r?E(i,I,"$1"):t||e})),n},O=function(e,t){var r,n=e;if(v(y,n)&&(n="%"+(r=y[n])[0]+"%"),v(g,n)){var o=g[n];if(o===h&&(o=m(n)),void 0===o&&!t)throw new a("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:o}}throw new i("intrinsic "+e+" does not exist!")};e.exports=function(e,t){if("string"!=typeof e||0===e.length)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new a('"allowMissing" argument must be a boolean');if(null===T(/^%?[^%]*%?$/,e))throw new i("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=x(e),n=r.length>0?r[0]:"",o=O("%"+n+"%",t),s=o.name,u=o.value,l=!1,d=o.alias;d&&(n=d[0],_(r,w([0,1],d)));for(var f=1,h=!0;f=r.length){var b=c(u,p);u=(h=!!b)&&"get"in b&&!("originalValue"in b.get)?b.get:u[p]}else h=v(u,p),u=u[p];h&&!l&&(g[s]=u)}}return u}},27296:(e,t,r)=>{"use strict";var n=r(40210)("%Object.getOwnPropertyDescriptor%",!0);if(n)try{n([],"length")}catch(e){n=null}e.exports=n},31044:(e,t,r)=>{"use strict";var n=r(40210)("%Object.defineProperty%",!0),i=function(){if(n)try{return n({},"a",{value:1}),!0}catch(e){return!1}return!1};i.hasArrayLengthDefineBug=function(){if(!i())return null;try{return 1!==n([],"length",{value:1}).length}catch(e){return!0}},e.exports=i},41405:(e,t,r)=>{"use strict";var n="undefined"!=typeof Symbol&&Symbol,i=r(55419);e.exports=function(){return"function"==typeof n&&"function"==typeof Symbol&&"symbol"==typeof n("foo")&&"symbol"==typeof Symbol("bar")&&i()}},55419:e=>{"use strict";e.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var n=Object.getOwnPropertySymbols(e);if(1!==n.length||n[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(e,t);if(42!==i.value||!0!==i.enumerable)return!1}return!0}},96410:(e,t,r)=>{"use strict";var n=r(55419);e.exports=function(){return n()&&!!Symbol.toStringTag}},17642:(e,t,r)=>{"use strict";var n=r(58612);e.exports=n.call(Function.call,Object.prototype.hasOwnProperty)},3349:(e,t,r)=>{"use strict";var n=r(89509).Buffer,i=r(88473).Transform;function o(e){i.call(this),this._block=n.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}r(35717)(o,i),o.prototype._transform=function(e,t,r){var n=null;try{this.update(e,t)}catch(e){n=e}r(n)},o.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(e){t=e}e(t)},o.prototype.update=function(e,t){if(function(e,t){if(!n.isBuffer(e)&&"string"!=typeof e)throw new TypeError("Data must be a string or a buffer")}(e),this._finalized)throw new Error("Digest already called");n.isBuffer(e)||(e=n.from(e,t));for(var r=this._block,i=0;this._blockOffset+e.length-i>=this._blockSize;){for(var o=this._blockOffset;o0;++a)this._length[a]+=s,(s=this._length[a]/4294967296|0)>0&&(this._length[a]-=4294967296*s);return this},o.prototype._update=function(){throw new Error("_update is not implemented")},o.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();void 0!==e&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t},o.prototype._digest=function(){throw new Error("_digest is not implemented")},e.exports=o},33715:(e,t,r)=>{var n=t;n.utils=r(26436),n.common=r(95772),n.sha=r(89041),n.ripemd=r(12949),n.hmac=r(52344),n.sha1=n.sha.sha1,n.sha256=n.sha.sha256,n.sha224=n.sha.sha224,n.sha384=n.sha.sha384,n.sha512=n.sha.sha512,n.ripemd160=n.ripemd.ripemd160},95772:(e,t,r)=>{"use strict";var n=r(26436),i=r(79746);function o(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}t.BlockHash=o,o.prototype.update=function(e,t){if(e=n.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var r=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-r,e.length),0===this.pending.length&&(this.pending=null),e=n.join32(e,0,e.length-r,this.endian);for(var i=0;i>>24&255,n[i++]=e>>>16&255,n[i++]=e>>>8&255,n[i++]=255&e}else for(n[i++]=255&e,n[i++]=e>>>8&255,n[i++]=e>>>16&255,n[i++]=e>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;o{"use strict";var n=r(26436),i=r(79746);function o(e,t,r){if(!(this instanceof o))return new o(e,t,r);this.Hash=e,this.blockSize=e.blockSize/8,this.outSize=e.outSize/8,this.inner=null,this.outer=null,this._init(n.toArray(t,r))}e.exports=o,o.prototype._init=function(e){e.length>this.blockSize&&(e=(new this.Hash).update(e).digest()),i(e.length<=this.blockSize);for(var t=e.length;t{"use strict";var n=r(26436),i=r(95772),o=n.rotl32,a=n.sum32,s=n.sum32_3,c=n.sum32_4,u=i.BlockHash;function l(){if(!(this instanceof l))return new l;u.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}function d(e,t,r,n){return e<=15?t^r^n:e<=31?t&r|~t&n:e<=47?(t|~r)^n:e<=63?t&n|r&~n:t^(r|~n)}function f(e){return e<=15?0:e<=31?1518500249:e<=47?1859775393:e<=63?2400959708:2840853838}function h(e){return e<=15?1352829926:e<=31?1548603684:e<=47?1836072691:e<=63?2053994217:0}n.inherits(l,u),t.ripemd160=l,l.blockSize=512,l.outSize=160,l.hmacStrength=192,l.padLength=64,l.prototype._update=function(e,t){for(var r=this.h[0],n=this.h[1],i=this.h[2],u=this.h[3],l=this.h[4],b=r,v=n,w=i,_=u,E=l,S=0;S<80;S++){var T=a(o(c(r,d(S,n,i,u),e[p[S]+t],f(S)),m[S]),l);r=l,l=u,u=o(i,10),i=n,n=T,T=a(o(c(b,d(79-S,v,w,_),e[g[S]+t],h(S)),y[S]),E),b=E,E=_,_=o(w,10),w=v,v=T}T=s(this.h[1],i,_),this.h[1]=s(this.h[2],u,E),this.h[2]=s(this.h[3],l,b),this.h[3]=s(this.h[4],r,v),this.h[4]=s(this.h[0],n,w),this.h[0]=T},l.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h,"little"):n.split32(this.h,"little")};var p=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],g=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],m=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],y=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]},89041:(e,t,r)=>{"use strict";t.sha1=r(84761),t.sha224=r(10799),t.sha256=r(89344),t.sha384=r(80772),t.sha512=r(45900)},84761:(e,t,r)=>{"use strict";var n=r(26436),i=r(95772),o=r(37038),a=n.rotl32,s=n.sum32,c=n.sum32_5,u=o.ft_1,l=i.BlockHash,d=[1518500249,1859775393,2400959708,3395469782];function f(){if(!(this instanceof f))return new f;l.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}n.inherits(f,l),e.exports=f,f.blockSize=512,f.outSize=160,f.hmacStrength=80,f.padLength=64,f.prototype._update=function(e,t){for(var r=this.W,n=0;n<16;n++)r[n]=e[t+n];for(;n{"use strict";var n=r(26436),i=r(89344);function o(){if(!(this instanceof o))return new o;i.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}n.inherits(o,i),e.exports=o,o.blockSize=512,o.outSize=224,o.hmacStrength=192,o.padLength=64,o.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h.slice(0,7),"big"):n.split32(this.h.slice(0,7),"big")}},89344:(e,t,r)=>{"use strict";var n=r(26436),i=r(95772),o=r(37038),a=r(79746),s=n.sum32,c=n.sum32_4,u=n.sum32_5,l=o.ch32,d=o.maj32,f=o.s0_256,h=o.s1_256,p=o.g0_256,g=o.g1_256,m=i.BlockHash,y=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function b(){if(!(this instanceof b))return new b;m.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=y,this.W=new Array(64)}n.inherits(b,m),e.exports=b,b.blockSize=512,b.outSize=256,b.hmacStrength=192,b.padLength=64,b.prototype._update=function(e,t){for(var r=this.W,n=0;n<16;n++)r[n]=e[t+n];for(;n{"use strict";var n=r(26436),i=r(45900);function o(){if(!(this instanceof o))return new o;i.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]}n.inherits(o,i),e.exports=o,o.blockSize=1024,o.outSize=384,o.hmacStrength=192,o.padLength=128,o.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h.slice(0,12),"big"):n.split32(this.h.slice(0,12),"big")}},45900:(e,t,r)=>{"use strict";var n=r(26436),i=r(95772),o=r(79746),a=n.rotr64_hi,s=n.rotr64_lo,c=n.shr64_hi,u=n.shr64_lo,l=n.sum64,d=n.sum64_hi,f=n.sum64_lo,h=n.sum64_4_hi,p=n.sum64_4_lo,g=n.sum64_5_hi,m=n.sum64_5_lo,y=i.BlockHash,b=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function v(){if(!(this instanceof v))return new v;y.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=b,this.W=new Array(160)}function w(e,t,r,n,i){var o=e&r^~e&i;return o<0&&(o+=4294967296),o}function _(e,t,r,n,i,o){var a=t&n^~t&o;return a<0&&(a+=4294967296),a}function E(e,t,r,n,i){var o=e&r^e&i^r&i;return o<0&&(o+=4294967296),o}function S(e,t,r,n,i,o){var a=t&n^t&o^n&o;return a<0&&(a+=4294967296),a}function T(e,t){var r=a(e,t,28)^a(t,e,2)^a(t,e,7);return r<0&&(r+=4294967296),r}function A(e,t){var r=s(e,t,28)^s(t,e,2)^s(t,e,7);return r<0&&(r+=4294967296),r}function I(e,t){var r=s(e,t,14)^s(e,t,18)^s(t,e,9);return r<0&&(r+=4294967296),r}function x(e,t){var r=a(e,t,1)^a(e,t,8)^c(e,t,7);return r<0&&(r+=4294967296),r}function O(e,t){var r=s(e,t,1)^s(e,t,8)^u(e,t,7);return r<0&&(r+=4294967296),r}function k(e,t){var r=s(e,t,19)^s(t,e,29)^u(e,t,6);return r<0&&(r+=4294967296),r}n.inherits(v,y),e.exports=v,v.blockSize=1024,v.outSize=512,v.hmacStrength=192,v.padLength=128,v.prototype._prepareBlock=function(e,t){for(var r=this.W,n=0;n<32;n++)r[n]=e[t+n];for(;n{"use strict";var n=r(26436).rotr32;function i(e,t,r){return e&t^~e&r}function o(e,t,r){return e&t^e&r^t&r}function a(e,t,r){return e^t^r}t.ft_1=function(e,t,r,n){return 0===e?i(t,r,n):1===e||3===e?a(t,r,n):2===e?o(t,r,n):void 0},t.ch32=i,t.maj32=o,t.p32=a,t.s0_256=function(e){return n(e,2)^n(e,13)^n(e,22)},t.s1_256=function(e){return n(e,6)^n(e,11)^n(e,25)},t.g0_256=function(e){return n(e,7)^n(e,18)^e>>>3},t.g1_256=function(e){return n(e,17)^n(e,19)^e>>>10}},26436:(e,t,r)=>{"use strict";var n=r(79746),i=r(35717);function o(e,t){return 55296==(64512&e.charCodeAt(t))&&!(t<0||t+1>=e.length)&&56320==(64512&e.charCodeAt(t+1))}function a(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function s(e){return 1===e.length?"0"+e:e}function c(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}t.inherits=i,t.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),i=0;i>6|192,r[n++]=63&a|128):o(e,i)?(a=65536+((1023&a)<<10)+(1023&e.charCodeAt(++i)),r[n++]=a>>18|240,r[n++]=a>>12&63|128,r[n++]=a>>6&63|128,r[n++]=63&a|128):(r[n++]=a>>12|224,r[n++]=a>>6&63|128,r[n++]=63&a|128)}else for(i=0;i>>0}return a},t.split32=function(e,t){for(var r=new Array(4*e.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},t.rotr32=function(e,t){return e>>>t|e<<32-t},t.rotl32=function(e,t){return e<>>32-t},t.sum32=function(e,t){return e+t>>>0},t.sum32_3=function(e,t,r){return e+t+r>>>0},t.sum32_4=function(e,t,r,n){return e+t+r+n>>>0},t.sum32_5=function(e,t,r,n,i){return e+t+r+n+i>>>0},t.sum64=function(e,t,r,n){var i=e[t],o=n+e[t+1]>>>0,a=(o>>0,e[t+1]=o},t.sum64_hi=function(e,t,r,n){return(t+n>>>0>>0},t.sum64_lo=function(e,t,r,n){return t+n>>>0},t.sum64_4_hi=function(e,t,r,n,i,o,a,s){var c=0,u=t;return c+=(u=u+n>>>0)>>0)>>0)>>0},t.sum64_4_lo=function(e,t,r,n,i,o,a,s){return t+n+o+s>>>0},t.sum64_5_hi=function(e,t,r,n,i,o,a,s,c,u){var l=0,d=t;return l+=(d=d+n>>>0)>>0)>>0)>>0)>>0},t.sum64_5_lo=function(e,t,r,n,i,o,a,s,c,u){return t+n+o+s+u>>>0},t.rotr64_hi=function(e,t,r){return(t<<32-r|e>>>r)>>>0},t.rotr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0},t.shr64_hi=function(e,t,r){return e>>>r},t.shr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0}},49840:(e,t,r)=>{var n=r(69282),i=r(89509).Buffer,o=r(55835),a=r(58334),s=r(17221),c=i.from("Bitcoin seed","utf8"),u=2147483648,l={private:76066276,public:76067358};function d(e){this.versions=e||l,this.depth=0,this.index=0,this._privateKey=null,this._publicKey=null,this.chainCode=null,this._fingerprint=0,this.parentFingerprint=0}function f(e,t,r){var n=i.allocUnsafe(78);n.writeUInt32BE(t,0),n.writeUInt8(e.depth,4);var o=e.depth?e.parentFingerprint:0;return n.writeUInt32BE(o,5),n.writeUInt32BE(e.index,9),e.chainCode.copy(n,13),r.copy(n,45),n}function h(e){var t=o.createHash("sha256").update(e).digest();return o.createHash("ripemd160").update(t).digest()}Object.defineProperty(d.prototype,"fingerprint",{get:function(){return this._fingerprint}}),Object.defineProperty(d.prototype,"identifier",{get:function(){return this._identifier}}),Object.defineProperty(d.prototype,"pubKeyHash",{get:function(){return this.identifier}}),Object.defineProperty(d.prototype,"privateKey",{get:function(){return this._privateKey},set:function(e){n.equal(e.length,32,"Private key must be 32 bytes."),n(!0===s.privateKeyVerify(e),"Invalid private key"),this._privateKey=e,this._publicKey=i.from(s.publicKeyCreate(e,!0)),this._identifier=h(this.publicKey),this._fingerprint=this._identifier.slice(0,4).readUInt32BE(0)}}),Object.defineProperty(d.prototype,"publicKey",{get:function(){return this._publicKey},set:function(e){n(33===e.length||65===e.length,"Public key must be 33 or 65 bytes."),n(!0===s.publicKeyVerify(e),"Invalid public key"),this._publicKey=i.from(s.publicKeyConvert(e,!0)),this._identifier=h(this.publicKey),this._fingerprint=this._identifier.slice(0,4).readUInt32BE(0),this._privateKey=null}}),Object.defineProperty(d.prototype,"privateExtendedKey",{get:function(){return this._privateKey?a.encode(f(this,this.versions.private,i.concat([i.alloc(1,0),this.privateKey]))):null}}),Object.defineProperty(d.prototype,"publicExtendedKey",{get:function(){return a.encode(f(this,this.versions.public,this.publicKey))}}),d.prototype.derive=function(e){if("m"===e||"M"===e||"m'"===e||"M'"===e)return this;var t=e.split("/"),r=this;return t.forEach((function(e,t){if(0!==t){var i=e.length>1&&"'"===e[e.length-1],o=parseInt(e,10);n(o=u,a=i.allocUnsafe(4);if(a.writeUInt32BE(e,0),r){n(this.privateKey,"Could not derive hardened child key");var c=this.privateKey,l=i.alloc(1,0);c=i.concat([l,c]),t=i.concat([c,a])}else t=i.concat([this.publicKey,a]);var f=o.createHmac("sha512",this.chainCode).update(t).digest(),h=f.slice(0,32),p=f.slice(32),g=new d(this.versions);if(this.privateKey)try{g.privateKey=i.from(s.privateKeyTweakAdd(i.from(this.privateKey),h))}catch(t){return this.deriveChild(e+1)}else try{g.publicKey=i.from(s.publicKeyTweakAdd(i.from(this.publicKey),h,!0))}catch(t){return this.deriveChild(e+1)}return g.chainCode=p,g.depth=this.depth+1,g.parentFingerprint=this.fingerprint,g.index=e,g},d.prototype.sign=function(e){return i.from(s.ecdsaSign(e,this.privateKey).signature)},d.prototype.verify=function(e,t){return s.ecdsaVerify(Uint8Array.from(t),Uint8Array.from(e),Uint8Array.from(this.publicKey))},d.prototype.wipePrivateData=function(){return this._privateKey&&o.randomBytes(this._privateKey.length).copy(this._privateKey),this._privateKey=null,this},d.prototype.toJSON=function(){return{xpriv:this.privateExtendedKey,xpub:this.publicExtendedKey}},d.fromMasterSeed=function(e,t){var r=o.createHmac("sha512",c).update(e).digest(),n=r.slice(0,32),i=r.slice(32),a=new d(t);return a.chainCode=i,a.privateKey=n,a},d.fromExtendedKey=function(e,t){var r=new d(t=t||l),i=a.decode(e),o=i.readUInt32BE(0);n(o===t.private||o===t.public,"Version mismatch: does not match private or public"),r.depth=i.readUInt8(4),r.parentFingerprint=i.readUInt32BE(5),r.index=i.readUInt32BE(9),r.chainCode=i.slice(13,45);var s=i.slice(45);return 0===s.readUInt8(0)?(n(o===t.private,"Version mismatch: version does not match private"),r.privateKey=s.slice(1)):(n(o===t.public,"Version mismatch: version does not match public"),r.publicKey=s),r},d.fromJSON=function(e){return d.fromExtendedKey(e.xpriv)},d.HARDENED_OFFSET=u,e.exports=d},2156:(e,t,r)=>{"use strict";var n=r(33715),i=r(34504),o=r(79746);function a(e){if(!(this instanceof a))return new a(e);this.hash=e.hash,this.predResist=!!e.predResist,this.outLen=this.hash.outSize,this.minEntropy=e.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var t=i.toArray(e.entropy,e.entropyEnc||"hex"),r=i.toArray(e.nonce,e.nonceEnc||"hex"),n=i.toArray(e.pers,e.persEnc||"hex");o(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,r,n)}e.exports=a,a.prototype._init=function(e,t,r){var n=e.concat(t).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(r||[])),this._reseed=1},a.prototype.generate=function(e,t,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof t&&(n=r,r=t,t=null),r&&(r=i.toArray(r,n||"hex"),this._update(r));for(var o=[];o.length{t.read=function(e,t,r,n,i){var o,a,s=8*i-n-1,c=(1<>1,l=-7,d=r?i-1:0,f=r?-1:1,h=e[t+d];for(d+=f,o=h&(1<<-l)-1,h>>=-l,l+=s;l>0;o=256*o+e[t+d],d+=f,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=n;l>0;a=256*a+e[t+d],d+=f,l-=8);if(0===o)o=1-u;else{if(o===c)return a?NaN:1/0*(h?-1:1);a+=Math.pow(2,n),o-=u}return(h?-1:1)*a*Math.pow(2,o-n)},t.write=function(e,t,r,n,i,o){var a,s,c,u=8*o-i-1,l=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),(t+=a+d>=1?f/c:f*Math.pow(2,1-d))*c>=2&&(a++,c/=2),a+d>=l?(s=0,a=l):a+d>=1?(s=(t*c-1)*Math.pow(2,i),a+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,i),a=0));i>=8;e[r+h]=255&s,h+=p,s/=256,i-=8);for(a=a<0;e[r+h]=255&a,h+=p,a/=256,u-=8);e[r+h-p]|=128*g}},35717:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},41143:e=>{"use strict";e.exports=function(e,t,r,n,i,o,a,s){if(!e){var c;if(void 0===t)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[r,n,i,o,a,s],l=0;(c=new Error(t.replace(/%s/g,(function(){return u[l++]})))).name="Invariant Violation"}throw c.framesToPop=1,c}}},82584:(e,t,r)=>{"use strict";var n=r(96410)(),i=r(21924)("Object.prototype.toString"),o=function(e){return!(n&&e&&"object"==typeof e&&Symbol.toStringTag in e)&&"[object Arguments]"===i(e)},a=function(e){return!!o(e)||null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==i(e)&&"[object Function]"===i(e.callee)},s=function(){return o(arguments)}();o.isLegacyArguments=a,e.exports=s?o:a},95320:e=>{"use strict";var t,r,n=Function.prototype.toString,i="object"==typeof Reflect&&null!==Reflect&&Reflect.apply;if("function"==typeof i&&"function"==typeof Object.defineProperty)try{t=Object.defineProperty({},"length",{get:function(){throw r}}),r={},i((function(){throw 42}),null,t)}catch(e){e!==r&&(i=null)}else i=null;var o=/^\s*class\b/,a=function(e){try{var t=n.call(e);return o.test(t)}catch(e){return!1}},s=function(e){try{return!a(e)&&(n.call(e),!0)}catch(e){return!1}},c=Object.prototype.toString,u="function"==typeof Symbol&&!!Symbol.toStringTag,l=!(0 in[,]),d=function(){return!1};if("object"==typeof document){var f=document.all;c.call(f)===c.call(document.all)&&(d=function(e){if((l||!e)&&(void 0===e||"object"==typeof e))try{var t=c.call(e);return("[object HTMLAllCollection]"===t||"[object HTML document.all class]"===t||"[object HTMLCollection]"===t||"[object Object]"===t)&&null==e("")}catch(e){}return!1})}e.exports=i?function(e){if(d(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;try{i(e,null,t)}catch(e){if(e!==r)return!1}return!a(e)&&s(e)}:function(e){if(d(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;if(u)return s(e);if(a(e))return!1;var t=c.call(e);return!("[object Function]"!==t&&"[object GeneratorFunction]"!==t&&!/^\[object HTML/.test(t))&&s(e)}},48662:(e,t,r)=>{"use strict";var n,i=Object.prototype.toString,o=Function.prototype.toString,a=/^\s*(?:function)?\*/,s=r(96410)(),c=Object.getPrototypeOf;e.exports=function(e){if("function"!=typeof e)return!1;if(a.test(o.call(e)))return!0;if(!s)return"[object GeneratorFunction]"===i.call(e);if(!c)return!1;if(void 0===n){var t=function(){if(!s)return!1;try{return Function("return function*() {}")()}catch(e){}}();n=!!t&&c(t)}return c(e)===n}},98611:e=>{"use strict";e.exports=function(e){return e!=e}},20360:(e,t,r)=>{"use strict";var n=r(55559),i=r(4289),o=r(98611),a=r(29415),s=r(23194),c=n(a(),Number);i(c,{getPolyfill:a,implementation:o,shim:s}),e.exports=c},29415:(e,t,r)=>{"use strict";var n=r(98611);e.exports=function(){return Number.isNaN&&Number.isNaN(NaN)&&!Number.isNaN("a")?Number.isNaN:n}},23194:(e,t,r)=>{"use strict";var n=r(4289),i=r(29415);e.exports=function(){var e=i();return n(Number,{isNaN:e},{isNaN:function(){return Number.isNaN!==e}}),e}},85692:(e,t,r)=>{"use strict";var n=r(94029),i=r(63083),o=r(21924),a=o("Object.prototype.toString"),s=r(96410)(),c=r(27296),u="undefined"==typeof globalThis?r.g:globalThis,l=i(),d=o("Array.prototype.indexOf",!0)||function(e,t){for(var r=0;r-1}return!!c&&function(e){var t=!1;return n(h,(function(r,n){if(!t)try{t=r.call(e)===n}catch(e){}})),t}(e)}},19755:function(e,t){var r;!function(t,r){"use strict";"object"==typeof e.exports?e.exports=t.document?r(t,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return r(e)}:r(t)}("undefined"!=typeof window?window:this,(function(n,i){"use strict";var o=[],a=Object.getPrototypeOf,s=o.slice,c=o.flat?function(e){return o.flat.call(e)}:function(e){return o.concat.apply([],e)},u=o.push,l=o.indexOf,d={},f=d.toString,h=d.hasOwnProperty,p=h.toString,g=p.call(Object),m={},y=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},b=function(e){return null!=e&&e===e.window},v=n.document,w={type:!0,src:!0,nonce:!0,noModule:!0};function _(e,t,r){var n,i,o=(r=r||v).createElement("script");if(o.text=e,t)for(n in w)(i=t[n]||t.getAttribute&&t.getAttribute(n))&&o.setAttribute(n,i);r.head.appendChild(o).parentNode.removeChild(o)}function E(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?d[f.call(e)]||"object":typeof e}var S="3.6.3",T=function(e,t){return new T.fn.init(e,t)};function A(e){var t=!!e&&"length"in e&&e.length,r=E(e);return!y(e)&&!b(e)&&("array"===r||0===t||"number"==typeof t&&t>0&&t-1 in e)}T.fn=T.prototype={jquery:S,constructor:T,length:0,toArray:function(){return s.call(this)},get:function(e){return null==e?s.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=T.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return T.each(this,e)},map:function(e){return this.pushStack(T.map(this,(function(t,r){return e.call(t,r,t)})))},slice:function(){return this.pushStack(s.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},even:function(){return this.pushStack(T.grep(this,(function(e,t){return(t+1)%2})))},odd:function(){return this.pushStack(T.grep(this,(function(e,t){return t%2})))},eq:function(e){var t=this.length,r=+e+(e<0?t:0);return this.pushStack(r>=0&&r+~]|"+B+")"+B+"*"),K=new RegExp(B+"|>"),q=new RegExp(F),z=new RegExp("^"+U+"$"),G={ID:new RegExp("^#("+U+")"),CLASS:new RegExp("^\\.("+U+")"),TAG:new RegExp("^("+U+"|[*])"),ATTR:new RegExp("^"+j),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+B+"*(even|odd|(([+-]|)(\\d*)n|)"+B+"*(?:([+-]|)"+B+"*(\\d+)|))"+B+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+B+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+B+"*((?:-\\d)?\\d*)"+B+"*\\)|)(?=[^-]|$)","i")},X=/HTML$/i,Y=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,J=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+B+"?|\\\\([^\\r\\n\\f])","g"),re=function(e,t){var r="0x"+e.slice(1)-65536;return t||(r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320))},ne=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"�":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){f()},ae=we((function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()}),{dir:"parentNode",next:"legend"});try{M.apply(P=R.call(_.childNodes),_.childNodes),P[_.childNodes.length].nodeType}catch(e){M={apply:P.length?function(e,t){N.apply(e,R.call(t))}:function(e,t){for(var r=e.length,n=0;e[r++]=t[n++];);e.length=r-1}}}function se(e,t,n,i){var o,s,u,l,d,p,y,b=t&&t.ownerDocument,_=t?t.nodeType:9;if(n=n||[],"string"!=typeof e||!e||1!==_&&9!==_&&11!==_)return n;if(!i&&(f(t),t=t||h,g)){if(11!==_&&(d=Z.exec(e)))if(o=d[1]){if(9===_){if(!(u=t.getElementById(o)))return n;if(u.id===o)return n.push(u),n}else if(b&&(u=b.getElementById(o))&&v(t,u)&&u.id===o)return n.push(u),n}else{if(d[2])return M.apply(n,t.getElementsByTagName(e)),n;if((o=d[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(o)),n}if(r.qsa&&!x[e+" "]&&(!m||!m.test(e))&&(1!==_||"object"!==t.nodeName.toLowerCase())){if(y=e,b=t,1===_&&(K.test(e)||$.test(e))){for((b=ee.test(e)&&ye(t.parentNode)||t)===t&&r.scope||((l=t.getAttribute("id"))?l=l.replace(ne,ie):t.setAttribute("id",l=w)),s=(p=a(e)).length;s--;)p[s]=(l?"#"+l:":scope")+" "+ve(p[s]);y=p.join(",")}try{if(r.cssSupportsSelector&&!CSS.supports("selector(:is("+y+"))"))throw new Error;return M.apply(n,b.querySelectorAll(y)),n}catch(t){x(e,!0)}finally{l===w&&t.removeAttribute("id")}}}return c(e.replace(W,"$1"),t,n,i)}function ce(){var e=[];return function t(r,i){return e.push(r+" ")>n.cacheLength&&delete t[e.shift()],t[r+" "]=i}}function ue(e){return e[w]=!0,e}function le(e){var t=h.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function de(e,t){for(var r=e.split("|"),i=r.length;i--;)n.attrHandle[r[i]]=t}function fe(e,t){var r=t&&e,n=r&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(n)return n;if(r)for(;r=r.nextSibling;)if(r===t)return-1;return e?1:-1}function he(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}function pe(e){return function(t){var r=t.nodeName.toLowerCase();return("input"===r||"button"===r)&&t.type===e}}function ge(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ae(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function me(e){return ue((function(t){return t=+t,ue((function(r,n){for(var i,o=e([],r.length,t),a=o.length;a--;)r[i=o[a]]&&(r[i]=!(n[i]=r[i]))}))}))}function ye(e){return e&&void 0!==e.getElementsByTagName&&e}for(t in r=se.support={},o=se.isXML=function(e){var t=e&&e.namespaceURI,r=e&&(e.ownerDocument||e).documentElement;return!X.test(t||r&&r.nodeName||"HTML")},f=se.setDocument=function(e){var t,i,a=e?e.ownerDocument||e:_;return a!=h&&9===a.nodeType&&a.documentElement?(p=(h=a).documentElement,g=!o(h),_!=h&&(i=h.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",oe,!1):i.attachEvent&&i.attachEvent("onunload",oe)),r.scope=le((function(e){return p.appendChild(e).appendChild(h.createElement("div")),void 0!==e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length})),r.cssSupportsSelector=le((function(){return CSS.supports("selector(*)")&&h.querySelectorAll(":is(:jqfake)")&&!CSS.supports("selector(:is(*,:jqfake))")})),r.attributes=le((function(e){return e.className="i",!e.getAttribute("className")})),r.getElementsByTagName=le((function(e){return e.appendChild(h.createComment("")),!e.getElementsByTagName("*").length})),r.getElementsByClassName=J.test(h.getElementsByClassName),r.getById=le((function(e){return p.appendChild(e).id=w,!h.getElementsByName||!h.getElementsByName(w).length})),r.getById?(n.filter.ID=function(e){var t=e.replace(te,re);return function(e){return e.getAttribute("id")===t}},n.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var r=t.getElementById(e);return r?[r]:[]}}):(n.filter.ID=function(e){var t=e.replace(te,re);return function(e){var r=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return r&&r.value===t}},n.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var r,n,i,o=t.getElementById(e);if(o){if((r=o.getAttributeNode("id"))&&r.value===e)return[o];for(i=t.getElementsByName(e),n=0;o=i[n++];)if((r=o.getAttributeNode("id"))&&r.value===e)return[o]}return[]}}),n.find.TAG=r.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):r.qsa?t.querySelectorAll(e):void 0}:function(e,t){var r,n=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;r=o[i++];)1===r.nodeType&&n.push(r);return n}return o},n.find.CLASS=r.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&g)return t.getElementsByClassName(e)},y=[],m=[],(r.qsa=J.test(h.querySelectorAll))&&(le((function(e){var t;p.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&m.push("[*^$]="+B+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||m.push("\\["+B+"*(?:value|"+L+")"),e.querySelectorAll("[id~="+w+"-]").length||m.push("~="),(t=h.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||m.push("\\["+B+"*name"+B+"*="+B+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||m.push(":checked"),e.querySelectorAll("a#"+w+"+*").length||m.push(".#.+[+~]"),e.querySelectorAll("\\\f"),m.push("[\\r\\n\\f]")})),le((function(e){e.innerHTML="";var t=h.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&m.push("name"+B+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&m.push(":enabled",":disabled"),p.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&m.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),m.push(",.*:")}))),(r.matchesSelector=J.test(b=p.matches||p.webkitMatchesSelector||p.mozMatchesSelector||p.oMatchesSelector||p.msMatchesSelector))&&le((function(e){r.disconnectedMatch=b.call(e,"*"),b.call(e,"[s!='']:x"),y.push("!=",F)})),r.cssSupportsSelector||m.push(":has"),m=m.length&&new RegExp(m.join("|")),y=y.length&&new RegExp(y.join("|")),t=J.test(p.compareDocumentPosition),v=t||J.test(p.contains)?function(e,t){var r=9===e.nodeType&&e.documentElement||e,n=t&&t.parentNode;return e===n||!(!n||1!==n.nodeType||!(r.contains?r.contains(n):e.compareDocumentPosition&&16&e.compareDocumentPosition(n)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},O=t?function(e,t){if(e===t)return d=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!r.sortDetached&&t.compareDocumentPosition(e)===n?e==h||e.ownerDocument==_&&v(_,e)?-1:t==h||t.ownerDocument==_&&v(_,t)?1:l?D(l,e)-D(l,t):0:4&n?-1:1)}:function(e,t){if(e===t)return d=!0,0;var r,n=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==h?-1:t==h?1:i?-1:o?1:l?D(l,e)-D(l,t):0;if(i===o)return fe(e,t);for(r=e;r=r.parentNode;)a.unshift(r);for(r=t;r=r.parentNode;)s.unshift(r);for(;a[n]===s[n];)n++;return n?fe(a[n],s[n]):a[n]==_?-1:s[n]==_?1:0},h):h},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(f(e),r.matchesSelector&&g&&!x[t+" "]&&(!y||!y.test(t))&&(!m||!m.test(t)))try{var n=b.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){x(t,!0)}return se(t,h,null,[e]).length>0},se.contains=function(e,t){return(e.ownerDocument||e)!=h&&f(e),v(e,t)},se.attr=function(e,t){(e.ownerDocument||e)!=h&&f(e);var i=n.attrHandle[t.toLowerCase()],o=i&&k.call(n.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:r.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},se.escape=function(e){return(e+"").replace(ne,ie)},se.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},se.uniqueSort=function(e){var t,n=[],i=0,o=0;if(d=!r.detectDuplicates,l=!r.sortStable&&e.slice(0),e.sort(O),d){for(;t=e[o++];)t===e[o]&&(i=n.push(o));for(;i--;)e.splice(n[i],1)}return l=null,e},i=se.getText=function(e){var t,r="",n=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)r+=i(e)}else if(3===o||4===o)return e.nodeValue}else for(;t=e[n++];)r+=i(t);return r},n=se.selectors={cacheLength:50,createPseudo:ue,match:G,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,re),e[3]=(e[3]||e[4]||e[5]||"").replace(te,re),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,r=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":r&&q.test(r)&&(t=a(r,!0))&&(t=r.indexOf(")",r.length-t)-r.length)&&(e[0]=e[0].slice(0,t),e[2]=r.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,re).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=T[e+" "];return t||(t=new RegExp("(^|"+B+")"+e+"("+B+"|$)"))&&T(e,(function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")}))},ATTR:function(e,t,r){return function(n){var i=se.attr(n,e);return null==i?"!="===t:!t||(i+="","="===t?i===r:"!="===t?i!==r:"^="===t?r&&0===i.indexOf(r):"*="===t?r&&i.indexOf(r)>-1:"$="===t?r&&i.slice(-r.length)===r:"~="===t?(" "+i.replace(H," ")+" ").indexOf(r)>-1:"|="===t&&(i===r||i.slice(0,r.length+1)===r+"-"))}},CHILD:function(e,t,r,n,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===n&&0===i?function(e){return!!e.parentNode}:function(t,r,c){var u,l,d,f,h,p,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),b=!c&&!s,v=!1;if(m){if(o){for(;g;){for(f=t;f=f[g];)if(s?f.nodeName.toLowerCase()===y:1===f.nodeType)return!1;p=g="only"===e&&!p&&"nextSibling"}return!0}if(p=[a?m.firstChild:m.lastChild],a&&b){for(v=(h=(u=(l=(d=(f=m)[w]||(f[w]={}))[f.uniqueID]||(d[f.uniqueID]={}))[e]||[])[0]===E&&u[1])&&u[2],f=h&&m.childNodes[h];f=++h&&f&&f[g]||(v=h=0)||p.pop();)if(1===f.nodeType&&++v&&f===t){l[e]=[E,h,v];break}}else if(b&&(v=h=(u=(l=(d=(f=t)[w]||(f[w]={}))[f.uniqueID]||(d[f.uniqueID]={}))[e]||[])[0]===E&&u[1]),!1===v)for(;(f=++h&&f&&f[g]||(v=h=0)||p.pop())&&((s?f.nodeName.toLowerCase()!==y:1!==f.nodeType)||!++v||(b&&((l=(d=f[w]||(f[w]={}))[f.uniqueID]||(d[f.uniqueID]={}))[e]=[E,v]),f!==t)););return(v-=i)===n||v%n==0&&v/n>=0}}},PSEUDO:function(e,t){var r,i=n.pseudos[e]||n.setFilters[e.toLowerCase()]||se.error("unsupported pseudo: "+e);return i[w]?i(t):i.length>1?(r=[e,e,"",t],n.setFilters.hasOwnProperty(e.toLowerCase())?ue((function(e,r){for(var n,o=i(e,t),a=o.length;a--;)e[n=D(e,o[a])]=!(r[n]=o[a])})):function(e){return i(e,0,r)}):i}},pseudos:{not:ue((function(e){var t=[],r=[],n=s(e.replace(W,"$1"));return n[w]?ue((function(e,t,r,i){for(var o,a=n(e,null,i,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))})):function(e,i,o){return t[0]=e,n(t,null,o,r),t[0]=null,!r.pop()}})),has:ue((function(e){return function(t){return se(e,t).length>0}})),contains:ue((function(e){return e=e.replace(te,re),function(t){return(t.textContent||i(t)).indexOf(e)>-1}})),lang:ue((function(e){return z.test(e||"")||se.error("unsupported lang: "+e),e=e.replace(te,re).toLowerCase(),function(t){var r;do{if(r=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(r=r.toLowerCase())===e||0===r.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}})),target:function(t){var r=e.location&&e.location.hash;return r&&r.slice(1)===t.id},root:function(e){return e===p},focus:function(e){return e===h.activeElement&&(!h.hasFocus||h.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:ge(!1),disabled:ge(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!n.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return Y.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:me((function(){return[0]})),last:me((function(e,t){return[t-1]})),eq:me((function(e,t,r){return[r<0?r+t:r]})),even:me((function(e,t){for(var r=0;rt?t:r;--n>=0;)e.push(n);return e})),gt:me((function(e,t,r){for(var n=r<0?r+t:r;++n1?function(t,r,n){for(var i=e.length;i--;)if(!e[i](t,r,n))return!1;return!0}:e[0]}function Ee(e,t,r,n,i){for(var o,a=[],s=0,c=e.length,u=null!=t;s-1&&(o[u]=!(a[u]=d))}}else y=Ee(y===a?y.splice(p,y.length):y),i?i(null,a,y,c):M.apply(a,y)}))}function Te(e){for(var t,r,i,o=e.length,a=n.relative[e[0].type],s=a||n.relative[" "],c=a?1:0,l=we((function(e){return e===t}),s,!0),d=we((function(e){return D(t,e)>-1}),s,!0),f=[function(e,r,n){var i=!a&&(n||r!==u)||((t=r).nodeType?l(e,r,n):d(e,r,n));return t=null,i}];c1&&_e(f),c>1&&ve(e.slice(0,c-1).concat({value:" "===e[c-2].type?"*":""})).replace(W,"$1"),r,c0,i=e.length>0,o=function(o,a,s,c,l){var d,p,m,y=0,b="0",v=o&&[],w=[],_=u,S=o||i&&n.find.TAG("*",l),T=E+=null==_?1:Math.random()||.1,A=S.length;for(l&&(u=a==h||a||l);b!==A&&null!=(d=S[b]);b++){if(i&&d){for(p=0,a||d.ownerDocument==h||(f(d),s=!g);m=e[p++];)if(m(d,a||h,s)){c.push(d);break}l&&(E=T)}r&&((d=!m&&d)&&y--,o&&v.push(d))}if(y+=b,r&&b!==y){for(p=0;m=t[p++];)m(v,w,a,s);if(o){if(y>0)for(;b--;)v[b]||w[b]||(w[b]=C.call(c));w=Ee(w)}M.apply(c,w),l&&!o&&w.length>0&&y+t.length>1&&se.uniqueSort(c)}return l&&(E=T,u=_),v};return r?ue(o):o}(o,i)),s.selector=e}return s},c=se.select=function(e,t,r,i){var o,c,u,l,d,f="function"==typeof e&&e,h=!i&&a(e=f.selector||e);if(r=r||[],1===h.length){if((c=h[0]=h[0].slice(0)).length>2&&"ID"===(u=c[0]).type&&9===t.nodeType&&g&&n.relative[c[1].type]){if(!(t=(n.find.ID(u.matches[0].replace(te,re),t)||[])[0]))return r;f&&(t=t.parentNode),e=e.slice(c.shift().value.length)}for(o=G.needsContext.test(e)?0:c.length;o--&&(u=c[o],!n.relative[l=u.type]);)if((d=n.find[l])&&(i=d(u.matches[0].replace(te,re),ee.test(c[0].type)&&ye(t.parentNode)||t))){if(c.splice(o,1),!(e=i.length&&ve(c)))return M.apply(r,i),r;break}}return(f||s(e,h))(i,t,!g,r,!t||ee.test(e)&&ye(t.parentNode)||t),r},r.sortStable=w.split("").sort(O).join("")===w,r.detectDuplicates=!!d,f(),r.sortDetached=le((function(e){return 1&e.compareDocumentPosition(h.createElement("fieldset"))})),le((function(e){return e.innerHTML="","#"===e.firstChild.getAttribute("href")}))||de("type|href|height|width",(function(e,t,r){if(!r)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)})),r.attributes&&le((function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")}))||de("value",(function(e,t,r){if(!r&&"input"===e.nodeName.toLowerCase())return e.defaultValue})),le((function(e){return null==e.getAttribute("disabled")}))||de(L,(function(e,t,r){var n;if(!r)return!0===e[t]?t.toLowerCase():(n=e.getAttributeNode(t))&&n.specified?n.value:null})),se}(n);T.find=I,T.expr=I.selectors,T.expr[":"]=T.expr.pseudos,T.uniqueSort=T.unique=I.uniqueSort,T.text=I.getText,T.isXMLDoc=I.isXML,T.contains=I.contains,T.escapeSelector=I.escape;var x=function(e,t,r){for(var n=[],i=void 0!==r;(e=e[t])&&9!==e.nodeType;)if(1===e.nodeType){if(i&&T(e).is(r))break;n.push(e)}return n},O=function(e,t){for(var r=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&r.push(e);return r},k=T.expr.match.needsContext;function P(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var C=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function N(e,t,r){return y(t)?T.grep(e,(function(e,n){return!!t.call(e,n,e)!==r})):t.nodeType?T.grep(e,(function(e){return e===t!==r})):"string"!=typeof t?T.grep(e,(function(e){return l.call(t,e)>-1!==r})):T.filter(t,e,r)}T.filter=function(e,t,r){var n=t[0];return r&&(e=":not("+e+")"),1===t.length&&1===n.nodeType?T.find.matchesSelector(n,e)?[n]:[]:T.find.matches(e,T.grep(t,(function(e){return 1===e.nodeType})))},T.fn.extend({find:function(e){var t,r,n=this.length,i=this;if("string"!=typeof e)return this.pushStack(T(e).filter((function(){for(t=0;t1?T.uniqueSort(r):r},filter:function(e){return this.pushStack(N(this,e||[],!1))},not:function(e){return this.pushStack(N(this,e||[],!0))},is:function(e){return!!N(this,"string"==typeof e&&k.test(e)?T(e):e||[],!1).length}});var M,R=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(T.fn.init=function(e,t,r){var n,i;if(!e)return this;if(r=r||M,"string"==typeof e){if(!(n="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:R.exec(e))||!n[1]&&t)return!t||t.jquery?(t||r).find(e):this.constructor(t).find(e);if(n[1]){if(t=t instanceof T?t[0]:t,T.merge(this,T.parseHTML(n[1],t&&t.nodeType?t.ownerDocument||t:v,!0)),C.test(n[1])&&T.isPlainObject(t))for(n in t)y(this[n])?this[n](t[n]):this.attr(n,t[n]);return this}return(i=v.getElementById(n[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):y(e)?void 0!==r.ready?r.ready(e):e(T):T.makeArray(e,this)}).prototype=T.fn,M=T(v);var D=/^(?:parents|prev(?:Until|All))/,L={children:!0,contents:!0,next:!0,prev:!0};function B(e,t){for(;(e=e[t])&&1!==e.nodeType;);return e}T.fn.extend({has:function(e){var t=T(e,this),r=t.length;return this.filter((function(){for(var e=0;e-1:1===r.nodeType&&T.find.matchesSelector(r,e))){o.push(r);break}return this.pushStack(o.length>1?T.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?l.call(T(e),this[0]):l.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(T.uniqueSort(T.merge(this.get(),T(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),T.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x(e,"parentNode")},parentsUntil:function(e,t,r){return x(e,"parentNode",r)},next:function(e){return B(e,"nextSibling")},prev:function(e){return B(e,"previousSibling")},nextAll:function(e){return x(e,"nextSibling")},prevAll:function(e){return x(e,"previousSibling")},nextUntil:function(e,t,r){return x(e,"nextSibling",r)},prevUntil:function(e,t,r){return x(e,"previousSibling",r)},siblings:function(e){return O((e.parentNode||{}).firstChild,e)},children:function(e){return O(e.firstChild)},contents:function(e){return null!=e.contentDocument&&a(e.contentDocument)?e.contentDocument:(P(e,"template")&&(e=e.content||e),T.merge([],e.childNodes))}},(function(e,t){T.fn[e]=function(r,n){var i=T.map(this,t,r);return"Until"!==e.slice(-5)&&(n=r),n&&"string"==typeof n&&(i=T.filter(n,i)),this.length>1&&(L[e]||T.uniqueSort(i),D.test(e)&&i.reverse()),this.pushStack(i)}}));var U=/[^\x20\t\r\n\f]+/g;function j(e){return e}function F(e){throw e}function H(e,t,r,n){var i;try{e&&y(i=e.promise)?i.call(e).done(t).fail(r):e&&y(i=e.then)?i.call(e,t,r):t.apply(void 0,[e].slice(n))}catch(e){r.apply(void 0,[e])}}T.Callbacks=function(e){e="string"==typeof e?function(e){var t={};return T.each(e.match(U)||[],(function(e,r){t[r]=!0})),t}(e):T.extend({},e);var t,r,n,i,o=[],a=[],s=-1,c=function(){for(i=i||e.once,n=t=!0;a.length;s=-1)for(r=a.shift();++s-1;)o.splice(r,1),r<=s&&s--})),this},has:function(e){return e?T.inArray(e,o)>-1:o.length>0},empty:function(){return o&&(o=[]),this},disable:function(){return i=a=[],o=r="",this},disabled:function(){return!o},lock:function(){return i=a=[],r||t||(o=r=""),this},locked:function(){return!!i},fireWith:function(e,r){return i||(r=[e,(r=r||[]).slice?r.slice():r],a.push(r),t||c()),this},fire:function(){return u.fireWith(this,arguments),this},fired:function(){return!!n}};return u},T.extend({Deferred:function(e){var t=[["notify","progress",T.Callbacks("memory"),T.Callbacks("memory"),2],["resolve","done",T.Callbacks("once memory"),T.Callbacks("once memory"),0,"resolved"],["reject","fail",T.Callbacks("once memory"),T.Callbacks("once memory"),1,"rejected"]],r="pending",i={state:function(){return r},always:function(){return o.done(arguments).fail(arguments),this},catch:function(e){return i.then(null,e)},pipe:function(){var e=arguments;return T.Deferred((function(r){T.each(t,(function(t,n){var i=y(e[n[4]])&&e[n[4]];o[n[1]]((function(){var e=i&&i.apply(this,arguments);e&&y(e.promise)?e.promise().progress(r.notify).done(r.resolve).fail(r.reject):r[n[0]+"With"](this,i?[e]:arguments)}))})),e=null})).promise()},then:function(e,r,i){var o=0;function a(e,t,r,i){return function(){var s=this,c=arguments,u=function(){var n,u;if(!(e=o&&(r!==F&&(s=void 0,c=[n]),t.rejectWith(s,c))}};e?l():(T.Deferred.getStackHook&&(l.stackTrace=T.Deferred.getStackHook()),n.setTimeout(l))}}return T.Deferred((function(n){t[0][3].add(a(0,n,y(i)?i:j,n.notifyWith)),t[1][3].add(a(0,n,y(e)?e:j)),t[2][3].add(a(0,n,y(r)?r:F))})).promise()},promise:function(e){return null!=e?T.extend(e,i):i}},o={};return T.each(t,(function(e,n){var a=n[2],s=n[5];i[n[1]]=a.add,s&&a.add((function(){r=s}),t[3-e][2].disable,t[3-e][3].disable,t[0][2].lock,t[0][3].lock),a.add(n[3].fire),o[n[0]]=function(){return o[n[0]+"With"](this===o?void 0:this,arguments),this},o[n[0]+"With"]=a.fireWith})),i.promise(o),e&&e.call(o,o),o},when:function(e){var t=arguments.length,r=t,n=Array(r),i=s.call(arguments),o=T.Deferred(),a=function(e){return function(r){n[e]=this,i[e]=arguments.length>1?s.call(arguments):r,--t||o.resolveWith(n,i)}};if(t<=1&&(H(e,o.done(a(r)).resolve,o.reject,!t),"pending"===o.state()||y(i[r]&&i[r].then)))return o.then();for(;r--;)H(i[r],a(r),o.reject);return o.promise()}});var W=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;T.Deferred.exceptionHook=function(e,t){n.console&&n.console.warn&&e&&W.test(e.name)&&n.console.warn("jQuery.Deferred exception: "+e.message,e.stack,t)},T.readyException=function(e){n.setTimeout((function(){throw e}))};var V=T.Deferred();function $(){v.removeEventListener("DOMContentLoaded",$),n.removeEventListener("load",$),T.ready()}T.fn.ready=function(e){return V.then(e).catch((function(e){T.readyException(e)})),this},T.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--T.readyWait:T.isReady)||(T.isReady=!0,!0!==e&&--T.readyWait>0||V.resolveWith(v,[T]))}}),T.ready.then=V.then,"complete"===v.readyState||"loading"!==v.readyState&&!v.documentElement.doScroll?n.setTimeout(T.ready):(v.addEventListener("DOMContentLoaded",$),n.addEventListener("load",$));var K=function(e,t,r,n,i,o,a){var s=0,c=e.length,u=null==r;if("object"===E(r))for(s in i=!0,r)K(e,t,s,r[s],!0,o,a);else if(void 0!==n&&(i=!0,y(n)||(a=!0),u&&(a?(t.call(e,n),t=null):(u=t,t=function(e,t,r){return u.call(T(e),r)})),t))for(;s1,null,!0)},removeData:function(e){return this.each((function(){Z.remove(this,e)}))}}),T.extend({queue:function(e,t,r){var n;if(e)return t=(t||"fx")+"queue",n=J.get(e,t),r&&(!n||Array.isArray(r)?n=J.access(e,t,T.makeArray(r)):n.push(r)),n||[]},dequeue:function(e,t){t=t||"fx";var r=T.queue(e,t),n=r.length,i=r.shift(),o=T._queueHooks(e,t);"inprogress"===i&&(i=r.shift(),n--),i&&("fx"===t&&r.unshift("inprogress"),delete o.stop,i.call(e,(function(){T.dequeue(e,t)}),o)),!n&&o&&o.empty.fire()},_queueHooks:function(e,t){var r=t+"queueHooks";return J.get(e,r)||J.access(e,r,{empty:T.Callbacks("once memory").add((function(){J.remove(e,[t+"queue",r])}))})}}),T.fn.extend({queue:function(e,t){var r=2;return"string"!=typeof e&&(t=e,e="fx",r--),arguments.length\x20\t\r\n\f]*)/i,be=/^$|^module$|\/(?:java|ecma)script/i;pe=v.createDocumentFragment().appendChild(v.createElement("div")),(ge=v.createElement("input")).setAttribute("type","radio"),ge.setAttribute("checked","checked"),ge.setAttribute("name","t"),pe.appendChild(ge),m.checkClone=pe.cloneNode(!0).cloneNode(!0).lastChild.checked,pe.innerHTML="",m.noCloneChecked=!!pe.cloneNode(!0).lastChild.defaultValue,pe.innerHTML="",m.option=!!pe.lastChild;var ve={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function we(e,t){var r;return r=void 0!==e.getElementsByTagName?e.getElementsByTagName(t||"*"):void 0!==e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&P(e,t)?T.merge([e],r):r}function _e(e,t){for(var r=0,n=e.length;r",""]);var Ee=/<|&#?\w+;/;function Se(e,t,r,n,i){for(var o,a,s,c,u,l,d=t.createDocumentFragment(),f=[],h=0,p=e.length;h-1)i&&i.push(o);else if(u=se(o),a=we(d.appendChild(o),"script"),u&&_e(a),r)for(l=0;o=a[l++];)be.test(o.type||"")&&r.push(o);return d}var Te=/^([^.]*)(?:\.(.+)|)/;function Ae(){return!0}function Ie(){return!1}function xe(e,t){return e===function(){try{return v.activeElement}catch(e){}}()==("focus"===t)}function Oe(e,t,r,n,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof r&&(n=n||r,r=void 0),t)Oe(e,s,r,n,t[s],o);return e}if(null==n&&null==i?(i=r,n=r=void 0):null==i&&("string"==typeof r?(i=n,n=void 0):(i=n,n=r,r=void 0)),!1===i)i=Ie;else if(!i)return e;return 1===o&&(a=i,i=function(e){return T().off(e),a.apply(this,arguments)},i.guid=a.guid||(a.guid=T.guid++)),e.each((function(){T.event.add(this,t,i,n,r)}))}function ke(e,t,r){r?(J.set(e,t,!1),T.event.add(e,t,{namespace:!1,handler:function(e){var n,i,o=J.get(this,t);if(1&e.isTrigger&&this[t]){if(o.length)(T.event.special[t]||{}).delegateType&&e.stopPropagation();else if(o=s.call(arguments),J.set(this,t,o),n=r(this,t),this[t](),o!==(i=J.get(this,t))||n?J.set(this,t,!1):i={},o!==i)return e.stopImmediatePropagation(),e.preventDefault(),i&&i.value}else o.length&&(J.set(this,t,{value:T.event.trigger(T.extend(o[0],T.Event.prototype),o.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===J.get(e,t)&&T.event.add(e,t,Ae)}T.event={global:{},add:function(e,t,r,n,i){var o,a,s,c,u,l,d,f,h,p,g,m=J.get(e);if(Y(e))for(r.handler&&(r=(o=r).handler,i=o.selector),i&&T.find.matchesSelector(ae,i),r.guid||(r.guid=T.guid++),(c=m.events)||(c=m.events=Object.create(null)),(a=m.handle)||(a=m.handle=function(t){return void 0!==T&&T.event.triggered!==t.type?T.event.dispatch.apply(e,arguments):void 0}),u=(t=(t||"").match(U)||[""]).length;u--;)h=g=(s=Te.exec(t[u])||[])[1],p=(s[2]||"").split(".").sort(),h&&(d=T.event.special[h]||{},h=(i?d.delegateType:d.bindType)||h,d=T.event.special[h]||{},l=T.extend({type:h,origType:g,data:n,handler:r,guid:r.guid,selector:i,needsContext:i&&T.expr.match.needsContext.test(i),namespace:p.join(".")},o),(f=c[h])||((f=c[h]=[]).delegateCount=0,d.setup&&!1!==d.setup.call(e,n,p,a)||e.addEventListener&&e.addEventListener(h,a)),d.add&&(d.add.call(e,l),l.handler.guid||(l.handler.guid=r.guid)),i?f.splice(f.delegateCount++,0,l):f.push(l),T.event.global[h]=!0)},remove:function(e,t,r,n,i){var o,a,s,c,u,l,d,f,h,p,g,m=J.hasData(e)&&J.get(e);if(m&&(c=m.events)){for(u=(t=(t||"").match(U)||[""]).length;u--;)if(h=g=(s=Te.exec(t[u])||[])[1],p=(s[2]||"").split(".").sort(),h){for(d=T.event.special[h]||{},f=c[h=(n?d.delegateType:d.bindType)||h]||[],s=s[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=f.length;o--;)l=f[o],!i&&g!==l.origType||r&&r.guid!==l.guid||s&&!s.test(l.namespace)||n&&n!==l.selector&&("**"!==n||!l.selector)||(f.splice(o,1),l.selector&&f.delegateCount--,d.remove&&d.remove.call(e,l));a&&!f.length&&(d.teardown&&!1!==d.teardown.call(e,p,m.handle)||T.removeEvent(e,h,m.handle),delete c[h])}else for(h in c)T.event.remove(e,h+t[u],r,n,!0);T.isEmptyObject(c)&&J.remove(e,"handle events")}},dispatch:function(e){var t,r,n,i,o,a,s=new Array(arguments.length),c=T.event.fix(e),u=(J.get(this,"events")||Object.create(null))[c.type]||[],l=T.event.special[c.type]||{};for(s[0]=c,t=1;t=1))for(;u!==this;u=u.parentNode||this)if(1===u.nodeType&&("click"!==e.type||!0!==u.disabled)){for(o=[],a={},r=0;r-1:T.find(i,this,null,[u]).length),a[i]&&o.push(n);o.length&&s.push({elem:u,handlers:o})}return u=this,c\s*$/g;function Me(e,t){return P(e,"table")&&P(11!==t.nodeType?t:t.firstChild,"tr")&&T(e).children("tbody")[0]||e}function Re(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function De(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Le(e,t){var r,n,i,o,a,s;if(1===t.nodeType){if(J.hasData(e)&&(s=J.get(e).events))for(i in J.remove(t,"handle events"),s)for(r=0,n=s[i].length;r1&&"string"==typeof p&&!m.checkClone&&Ce.test(p))return e.each((function(i){var o=e.eq(i);g&&(t[0]=p.call(this,i,o.html())),Ue(o,t,r,n)}));if(f&&(o=(i=Se(t,e[0].ownerDocument,!1,e,n)).firstChild,1===i.childNodes.length&&(i=o),o||n)){for(s=(a=T.map(we(i,"script"),Re)).length;d0&&_e(a,!c&&we(e,"script")),s},cleanData:function(e){for(var t,r,n,i=T.event.special,o=0;void 0!==(r=e[o]);o++)if(Y(r)){if(t=r[J.expando]){if(t.events)for(n in t.events)i[n]?T.event.remove(r,n):T.removeEvent(r,n,t.handle);r[J.expando]=void 0}r[Z.expando]&&(r[Z.expando]=void 0)}}}),T.fn.extend({detach:function(e){return je(this,e,!0)},remove:function(e){return je(this,e)},text:function(e){return K(this,(function(e){return void 0===e?T.text(this):this.empty().each((function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)}))}),null,e,arguments.length)},append:function(){return Ue(this,arguments,(function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Me(this,e).appendChild(e)}))},prepend:function(){return Ue(this,arguments,(function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Me(this,e);t.insertBefore(e,t.firstChild)}}))},before:function(){return Ue(this,arguments,(function(e){this.parentNode&&this.parentNode.insertBefore(e,this)}))},after:function(){return Ue(this,arguments,(function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)}))},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(T.cleanData(we(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map((function(){return T.clone(this,e,t)}))},html:function(e){return K(this,(function(e){var t=this[0]||{},r=0,n=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Pe.test(e)&&!ve[(ye.exec(e)||["",""])[1].toLowerCase()]){e=T.htmlPrefilter(e);try{for(;r=0&&(c+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-c-s-.5))||0),c}function it(e,t,r){var n=We(e),i=(!m.boxSizingReliable()||r)&&"border-box"===T.css(e,"boxSizing",!1,n),o=i,a=ze(e,t,n),s="offset"+t[0].toUpperCase()+t.slice(1);if(Fe.test(a)){if(!r)return a;a="auto"}return(!m.boxSizingReliable()&&i||!m.reliableTrDimensions()&&P(e,"tr")||"auto"===a||!parseFloat(a)&&"inline"===T.css(e,"display",!1,n))&&e.getClientRects().length&&(i="border-box"===T.css(e,"boxSizing",!1,n),(o=s in e)&&(a=e[s])),(a=parseFloat(a)||0)+nt(e,t,r||(i?"border":"content"),o,n,a)+"px"}function ot(e,t,r,n,i){return new ot.prototype.init(e,t,r,n,i)}T.extend({cssHooks:{opacity:{get:function(e,t){if(t){var r=ze(e,"opacity");return""===r?"1":r}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,r,n){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=X(t),c=He.test(t),u=e.style;if(c||(t=Je(s)),a=T.cssHooks[t]||T.cssHooks[s],void 0===r)return a&&"get"in a&&void 0!==(i=a.get(e,!1,n))?i:u[t];"string"==(o=typeof r)&&(i=ie.exec(r))&&i[1]&&(r=le(e,t,i),o="number"),null!=r&&r==r&&("number"!==o||c||(r+=i&&i[3]||(T.cssNumber[s]?"":"px")),m.clearCloneStyle||""!==r||0!==t.indexOf("background")||(u[t]="inherit"),a&&"set"in a&&void 0===(r=a.set(e,r,n))||(c?u.setProperty(t,r):u[t]=r))}},css:function(e,t,r,n){var i,o,a,s=X(t);return He.test(t)||(t=Je(s)),(a=T.cssHooks[t]||T.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,r)),void 0===i&&(i=ze(e,t,n)),"normal"===i&&t in tt&&(i=tt[t]),""===r||r?(o=parseFloat(i),!0===r||isFinite(o)?o||0:i):i}}),T.each(["height","width"],(function(e,t){T.cssHooks[t]={get:function(e,r,n){if(r)return!Ze.test(T.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?it(e,t,n):Ve(e,et,(function(){return it(e,t,n)}))},set:function(e,r,n){var i,o=We(e),a=!m.scrollboxSize()&&"absolute"===o.position,s=(a||n)&&"border-box"===T.css(e,"boxSizing",!1,o),c=n?nt(e,t,n,s,o):0;return s&&a&&(c-=Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-parseFloat(o[t])-nt(e,t,"border",!1,o)-.5)),c&&(i=ie.exec(r))&&"px"!==(i[3]||"px")&&(e.style[t]=r,r=T.css(e,t)),rt(0,r,c)}}})),T.cssHooks.marginLeft=Ge(m.reliableMarginLeft,(function(e,t){if(t)return(parseFloat(ze(e,"marginLeft"))||e.getBoundingClientRect().left-Ve(e,{marginLeft:0},(function(){return e.getBoundingClientRect().left})))+"px"})),T.each({margin:"",padding:"",border:"Width"},(function(e,t){T.cssHooks[e+t]={expand:function(r){for(var n=0,i={},o="string"==typeof r?r.split(" "):[r];n<4;n++)i[e+oe[n]+t]=o[n]||o[n-2]||o[0];return i}},"margin"!==e&&(T.cssHooks[e+t].set=rt)})),T.fn.extend({css:function(e,t){return K(this,(function(e,t,r){var n,i,o={},a=0;if(Array.isArray(t)){for(n=We(e),i=t.length;a1)}}),T.Tween=ot,ot.prototype={constructor:ot,init:function(e,t,r,n,i,o){this.elem=e,this.prop=r,this.easing=i||T.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=n,this.unit=o||(T.cssNumber[r]?"":"px")},cur:function(){var e=ot.propHooks[this.prop];return e&&e.get?e.get(this):ot.propHooks._default.get(this)},run:function(e){var t,r=ot.propHooks[this.prop];return this.options.duration?this.pos=t=T.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),r&&r.set?r.set(this):ot.propHooks._default.set(this),this}},ot.prototype.init.prototype=ot.prototype,ot.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=T.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){T.fx.step[e.prop]?T.fx.step[e.prop](e):1!==e.elem.nodeType||!T.cssHooks[e.prop]&&null==e.elem.style[Je(e.prop)]?e.elem[e.prop]=e.now:T.style(e.elem,e.prop,e.now+e.unit)}}},ot.propHooks.scrollTop=ot.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},T.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},T.fx=ot.prototype.init,T.fx.step={};var at,st,ct=/^(?:toggle|show|hide)$/,ut=/queueHooks$/;function lt(){st&&(!1===v.hidden&&n.requestAnimationFrame?n.requestAnimationFrame(lt):n.setTimeout(lt,T.fx.interval),T.fx.tick())}function dt(){return n.setTimeout((function(){at=void 0})),at=Date.now()}function ft(e,t){var r,n=0,i={height:e};for(t=t?1:0;n<4;n+=2-t)i["margin"+(r=oe[n])]=i["padding"+r]=e;return t&&(i.opacity=i.width=e),i}function ht(e,t,r){for(var n,i=(pt.tweeners[t]||[]).concat(pt.tweeners["*"]),o=0,a=i.length;o1)},removeAttr:function(e){return this.each((function(){T.removeAttr(this,e)}))}}),T.extend({attr:function(e,t,r){var n,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return void 0===e.getAttribute?T.prop(e,t,r):(1===o&&T.isXMLDoc(e)||(i=T.attrHooks[t.toLowerCase()]||(T.expr.match.bool.test(t)?gt:void 0)),void 0!==r?null===r?void T.removeAttr(e,t):i&&"set"in i&&void 0!==(n=i.set(e,r,t))?n:(e.setAttribute(t,r+""),r):i&&"get"in i&&null!==(n=i.get(e,t))?n:null==(n=T.find.attr(e,t))?void 0:n)},attrHooks:{type:{set:function(e,t){if(!m.radioValue&&"radio"===t&&P(e,"input")){var r=e.value;return e.setAttribute("type",t),r&&(e.value=r),t}}}},removeAttr:function(e,t){var r,n=0,i=t&&t.match(U);if(i&&1===e.nodeType)for(;r=i[n++];)e.removeAttribute(r)}}),gt={set:function(e,t,r){return!1===t?T.removeAttr(e,r):e.setAttribute(r,r),r}},T.each(T.expr.match.bool.source.match(/\w+/g),(function(e,t){var r=mt[t]||T.find.attr;mt[t]=function(e,t,n){var i,o,a=t.toLowerCase();return n||(o=mt[a],mt[a]=i,i=null!=r(e,t,n)?a:null,mt[a]=o),i}}));var yt=/^(?:input|select|textarea|button)$/i,bt=/^(?:a|area)$/i;function vt(e){return(e.match(U)||[]).join(" ")}function wt(e){return e.getAttribute&&e.getAttribute("class")||""}function _t(e){return Array.isArray(e)?e:"string"==typeof e&&e.match(U)||[]}T.fn.extend({prop:function(e,t){return K(this,T.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each((function(){delete this[T.propFix[e]||e]}))}}),T.extend({prop:function(e,t,r){var n,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&T.isXMLDoc(e)||(t=T.propFix[t]||t,i=T.propHooks[t]),void 0!==r?i&&"set"in i&&void 0!==(n=i.set(e,r,t))?n:e[t]=r:i&&"get"in i&&null!==(n=i.get(e,t))?n:e[t]},propHooks:{tabIndex:{get:function(e){var t=T.find.attr(e,"tabindex");return t?parseInt(t,10):yt.test(e.nodeName)||bt.test(e.nodeName)&&e.href?0:-1}}},propFix:{for:"htmlFor",class:"className"}}),m.optSelected||(T.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),T.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],(function(){T.propFix[this.toLowerCase()]=this})),T.fn.extend({addClass:function(e){var t,r,n,i,o,a;return y(e)?this.each((function(t){T(this).addClass(e.call(this,t,wt(this)))})):(t=_t(e)).length?this.each((function(){if(n=wt(this),r=1===this.nodeType&&" "+vt(n)+" "){for(o=0;o-1;)r=r.replace(" "+i+" "," ");a=vt(r),n!==a&&this.setAttribute("class",a)}})):this:this.attr("class","")},toggleClass:function(e,t){var r,n,i,o,a=typeof e,s="string"===a||Array.isArray(e);return y(e)?this.each((function(r){T(this).toggleClass(e.call(this,r,wt(this),t),t)})):"boolean"==typeof t&&s?t?this.addClass(e):this.removeClass(e):(r=_t(e),this.each((function(){if(s)for(o=T(this),i=0;i-1)return!0;return!1}});var Et=/\r/g;T.fn.extend({val:function(e){var t,r,n,i=this[0];return arguments.length?(n=y(e),this.each((function(r){var i;1===this.nodeType&&(null==(i=n?e.call(this,r,T(this).val()):e)?i="":"number"==typeof i?i+="":Array.isArray(i)&&(i=T.map(i,(function(e){return null==e?"":e+""}))),(t=T.valHooks[this.type]||T.valHooks[this.nodeName.toLowerCase()])&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))}))):i?(t=T.valHooks[i.type]||T.valHooks[i.nodeName.toLowerCase()])&&"get"in t&&void 0!==(r=t.get(i,"value"))?r:"string"==typeof(r=i.value)?r.replace(Et,""):null==r?"":r:void 0}}),T.extend({valHooks:{option:{get:function(e){var t=T.find.attr(e,"value");return null!=t?t:vt(T.text(e))}},select:{get:function(e){var t,r,n,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],c=a?o+1:i.length;for(n=o<0?c:a?o:0;n-1)&&(r=!0);return r||(e.selectedIndex=-1),o}}}}),T.each(["radio","checkbox"],(function(){T.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=T.inArray(T(e).val(),t)>-1}},m.checkOn||(T.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})})),m.focusin="onfocusin"in n;var St=/^(?:focusinfocus|focusoutblur)$/,Tt=function(e){e.stopPropagation()};T.extend(T.event,{trigger:function(e,t,r,i){var o,a,s,c,u,l,d,f,p=[r||v],g=h.call(e,"type")?e.type:e,m=h.call(e,"namespace")?e.namespace.split("."):[];if(a=f=s=r=r||v,3!==r.nodeType&&8!==r.nodeType&&!St.test(g+T.event.triggered)&&(g.indexOf(".")>-1&&(m=g.split("."),g=m.shift(),m.sort()),u=g.indexOf(":")<0&&"on"+g,(e=e[T.expando]?e:new T.Event(g,"object"==typeof e&&e)).isTrigger=i?2:3,e.namespace=m.join("."),e.rnamespace=e.namespace?new RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=r),t=null==t?[e]:T.makeArray(t,[e]),d=T.event.special[g]||{},i||!d.trigger||!1!==d.trigger.apply(r,t))){if(!i&&!d.noBubble&&!b(r)){for(c=d.delegateType||g,St.test(c+g)||(a=a.parentNode);a;a=a.parentNode)p.push(a),s=a;s===(r.ownerDocument||v)&&p.push(s.defaultView||s.parentWindow||n)}for(o=0;(a=p[o++])&&!e.isPropagationStopped();)f=a,e.type=o>1?c:d.bindType||g,(l=(J.get(a,"events")||Object.create(null))[e.type]&&J.get(a,"handle"))&&l.apply(a,t),(l=u&&a[u])&&l.apply&&Y(a)&&(e.result=l.apply(a,t),!1===e.result&&e.preventDefault());return e.type=g,i||e.isDefaultPrevented()||d._default&&!1!==d._default.apply(p.pop(),t)||!Y(r)||u&&y(r[g])&&!b(r)&&((s=r[u])&&(r[u]=null),T.event.triggered=g,e.isPropagationStopped()&&f.addEventListener(g,Tt),r[g](),e.isPropagationStopped()&&f.removeEventListener(g,Tt),T.event.triggered=void 0,s&&(r[u]=s)),e.result}},simulate:function(e,t,r){var n=T.extend(new T.Event,r,{type:e,isSimulated:!0});T.event.trigger(n,null,t)}}),T.fn.extend({trigger:function(e,t){return this.each((function(){T.event.trigger(e,t,this)}))},triggerHandler:function(e,t){var r=this[0];if(r)return T.event.trigger(e,t,r,!0)}}),m.focusin||T.each({focus:"focusin",blur:"focusout"},(function(e,t){var r=function(e){T.event.simulate(t,e.target,T.event.fix(e))};T.event.special[t]={setup:function(){var n=this.ownerDocument||this.document||this,i=J.access(n,t);i||n.addEventListener(e,r,!0),J.access(n,t,(i||0)+1)},teardown:function(){var n=this.ownerDocument||this.document||this,i=J.access(n,t)-1;i?J.access(n,t,i):(n.removeEventListener(e,r,!0),J.remove(n,t))}}}));var At=n.location,It={guid:Date.now()},xt=/\?/;T.parseXML=function(e){var t,r;if(!e||"string"!=typeof e)return null;try{t=(new n.DOMParser).parseFromString(e,"text/xml")}catch(e){}return r=t&&t.getElementsByTagName("parsererror")[0],t&&!r||T.error("Invalid XML: "+(r?T.map(r.childNodes,(function(e){return e.textContent})).join("\n"):e)),t};var Ot=/\[\]$/,kt=/\r?\n/g,Pt=/^(?:submit|button|image|reset|file)$/i,Ct=/^(?:input|select|textarea|keygen)/i;function Nt(e,t,r,n){var i;if(Array.isArray(t))T.each(t,(function(t,i){r||Ot.test(e)?n(e,i):Nt(e+"["+("object"==typeof i&&null!=i?t:"")+"]",i,r,n)}));else if(r||"object"!==E(t))n(e,t);else for(i in t)Nt(e+"["+i+"]",t[i],r,n)}T.param=function(e,t){var r,n=[],i=function(e,t){var r=y(t)?t():t;n[n.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==r?"":r)};if(null==e)return"";if(Array.isArray(e)||e.jquery&&!T.isPlainObject(e))T.each(e,(function(){i(this.name,this.value)}));else for(r in e)Nt(r,e[r],t,i);return n.join("&")},T.fn.extend({serialize:function(){return T.param(this.serializeArray())},serializeArray:function(){return this.map((function(){var e=T.prop(this,"elements");return e?T.makeArray(e):this})).filter((function(){var e=this.type;return this.name&&!T(this).is(":disabled")&&Ct.test(this.nodeName)&&!Pt.test(e)&&(this.checked||!me.test(e))})).map((function(e,t){var r=T(this).val();return null==r?null:Array.isArray(r)?T.map(r,(function(e){return{name:t.name,value:e.replace(kt,"\r\n")}})):{name:t.name,value:r.replace(kt,"\r\n")}})).get()}});var Mt=/%20/g,Rt=/#.*$/,Dt=/([?&])_=[^&]*/,Lt=/^(.*?):[ \t]*([^\r\n]*)$/gm,Bt=/^(?:GET|HEAD)$/,Ut=/^\/\//,jt={},Ft={},Ht="*/".concat("*"),Wt=v.createElement("a");function Vt(e){return function(t,r){"string"!=typeof t&&(r=t,t="*");var n,i=0,o=t.toLowerCase().match(U)||[];if(y(r))for(;n=o[i++];)"+"===n[0]?(n=n.slice(1)||"*",(e[n]=e[n]||[]).unshift(r)):(e[n]=e[n]||[]).push(r)}}function $t(e,t,r,n){var i={},o=e===Ft;function a(s){var c;return i[s]=!0,T.each(e[s]||[],(function(e,s){var u=s(t,r,n);return"string"!=typeof u||o||i[u]?o?!(c=u):void 0:(t.dataTypes.unshift(u),a(u),!1)})),c}return a(t.dataTypes[0])||!i["*"]&&a("*")}function Kt(e,t){var r,n,i=T.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((i[r]?e:n||(n={}))[r]=t[r]);return n&&T.extend(!0,e,n),e}Wt.href=At.href,T.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:At.href,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(At.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Ht,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":T.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Kt(Kt(e,T.ajaxSettings),t):Kt(T.ajaxSettings,e)},ajaxPrefilter:Vt(jt),ajaxTransport:Vt(Ft),ajax:function(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};var r,i,o,a,s,c,u,l,d,f,h=T.ajaxSetup({},t),p=h.context||h,g=h.context&&(p.nodeType||p.jquery)?T(p):T.event,m=T.Deferred(),y=T.Callbacks("once memory"),b=h.statusCode||{},w={},_={},E="canceled",S={readyState:0,getResponseHeader:function(e){var t;if(u){if(!a)for(a={};t=Lt.exec(o);)a[t[1].toLowerCase()+" "]=(a[t[1].toLowerCase()+" "]||[]).concat(t[2]);t=a[e.toLowerCase()+" "]}return null==t?null:t.join(", ")},getAllResponseHeaders:function(){return u?o:null},setRequestHeader:function(e,t){return null==u&&(e=_[e.toLowerCase()]=_[e.toLowerCase()]||e,w[e]=t),this},overrideMimeType:function(e){return null==u&&(h.mimeType=e),this},statusCode:function(e){var t;if(e)if(u)S.always(e[S.status]);else for(t in e)b[t]=[b[t],e[t]];return this},abort:function(e){var t=e||E;return r&&r.abort(t),A(0,t),this}};if(m.promise(S),h.url=((e||h.url||At.href)+"").replace(Ut,At.protocol+"//"),h.type=t.method||t.type||h.method||h.type,h.dataTypes=(h.dataType||"*").toLowerCase().match(U)||[""],null==h.crossDomain){c=v.createElement("a");try{c.href=h.url,c.href=c.href,h.crossDomain=Wt.protocol+"//"+Wt.host!=c.protocol+"//"+c.host}catch(e){h.crossDomain=!0}}if(h.data&&h.processData&&"string"!=typeof h.data&&(h.data=T.param(h.data,h.traditional)),$t(jt,h,t,S),u)return S;for(d in(l=T.event&&h.global)&&0==T.active++&&T.event.trigger("ajaxStart"),h.type=h.type.toUpperCase(),h.hasContent=!Bt.test(h.type),i=h.url.replace(Rt,""),h.hasContent?h.data&&h.processData&&0===(h.contentType||"").indexOf("application/x-www-form-urlencoded")&&(h.data=h.data.replace(Mt,"+")):(f=h.url.slice(i.length),h.data&&(h.processData||"string"==typeof h.data)&&(i+=(xt.test(i)?"&":"?")+h.data,delete h.data),!1===h.cache&&(i=i.replace(Dt,"$1"),f=(xt.test(i)?"&":"?")+"_="+It.guid+++f),h.url=i+f),h.ifModified&&(T.lastModified[i]&&S.setRequestHeader("If-Modified-Since",T.lastModified[i]),T.etag[i]&&S.setRequestHeader("If-None-Match",T.etag[i])),(h.data&&h.hasContent&&!1!==h.contentType||t.contentType)&&S.setRequestHeader("Content-Type",h.contentType),S.setRequestHeader("Accept",h.dataTypes[0]&&h.accepts[h.dataTypes[0]]?h.accepts[h.dataTypes[0]]+("*"!==h.dataTypes[0]?", "+Ht+"; q=0.01":""):h.accepts["*"]),h.headers)S.setRequestHeader(d,h.headers[d]);if(h.beforeSend&&(!1===h.beforeSend.call(p,S,h)||u))return S.abort();if(E="abort",y.add(h.complete),S.done(h.success),S.fail(h.error),r=$t(Ft,h,t,S)){if(S.readyState=1,l&&g.trigger("ajaxSend",[S,h]),u)return S;h.async&&h.timeout>0&&(s=n.setTimeout((function(){S.abort("timeout")}),h.timeout));try{u=!1,r.send(w,A)}catch(e){if(u)throw e;A(-1,e)}}else A(-1,"No Transport");function A(e,t,a,c){var d,f,v,w,_,E=t;u||(u=!0,s&&n.clearTimeout(s),r=void 0,o=c||"",S.readyState=e>0?4:0,d=e>=200&&e<300||304===e,a&&(w=function(e,t,r){for(var n,i,o,a,s=e.contents,c=e.dataTypes;"*"===c[0];)c.shift(),void 0===n&&(n=e.mimeType||t.getResponseHeader("Content-Type"));if(n)for(i in s)if(s[i]&&s[i].test(n)){c.unshift(i);break}if(c[0]in r)o=c[0];else{for(i in r){if(!c[0]||e.converters[i+" "+c[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==c[0]&&c.unshift(o),r[o]}(h,S,a)),!d&&T.inArray("script",h.dataTypes)>-1&&T.inArray("json",h.dataTypes)<0&&(h.converters["text script"]=function(){}),w=function(e,t,r,n){var i,o,a,s,c,u={},l=e.dataTypes.slice();if(l[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];for(o=l.shift();o;)if(e.responseFields[o]&&(r[e.responseFields[o]]=t),!c&&n&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),c=o,o=l.shift())if("*"===o)o=c;else if("*"!==c&&c!==o){if(!(a=u[c+" "+o]||u["* "+o]))for(i in u)if((s=i.split(" "))[1]===o&&(a=u[c+" "+s[0]]||u["* "+s[0]])){!0===a?a=u[i]:!0!==u[i]&&(o=s[0],l.unshift(s[1]));break}if(!0!==a)if(a&&e.throws)t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+c+" to "+o}}}return{state:"success",data:t}}(h,w,S,d),d?(h.ifModified&&((_=S.getResponseHeader("Last-Modified"))&&(T.lastModified[i]=_),(_=S.getResponseHeader("etag"))&&(T.etag[i]=_)),204===e||"HEAD"===h.type?E="nocontent":304===e?E="notmodified":(E=w.state,f=w.data,d=!(v=w.error))):(v=E,!e&&E||(E="error",e<0&&(e=0))),S.status=e,S.statusText=(t||E)+"",d?m.resolveWith(p,[f,E,S]):m.rejectWith(p,[S,E,v]),S.statusCode(b),b=void 0,l&&g.trigger(d?"ajaxSuccess":"ajaxError",[S,h,d?f:v]),y.fireWith(p,[S,E]),l&&(g.trigger("ajaxComplete",[S,h]),--T.active||T.event.trigger("ajaxStop")))}return S},getJSON:function(e,t,r){return T.get(e,t,r,"json")},getScript:function(e,t){return T.get(e,void 0,t,"script")}}),T.each(["get","post"],(function(e,t){T[t]=function(e,r,n,i){return y(r)&&(i=i||n,n=r,r=void 0),T.ajax(T.extend({url:e,type:t,dataType:i,data:r,success:n},T.isPlainObject(e)&&e))}})),T.ajaxPrefilter((function(e){var t;for(t in e.headers)"content-type"===t.toLowerCase()&&(e.contentType=e.headers[t]||"")})),T._evalUrl=function(e,t,r){return T.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,converters:{"text script":function(){}},dataFilter:function(e){T.globalEval(e,t,r)}})},T.fn.extend({wrapAll:function(e){var t;return this[0]&&(y(e)&&(e=e.call(this[0])),t=T(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map((function(){for(var e=this;e.firstElementChild;)e=e.firstElementChild;return e})).append(this)),this},wrapInner:function(e){return y(e)?this.each((function(t){T(this).wrapInner(e.call(this,t))})):this.each((function(){var t=T(this),r=t.contents();r.length?r.wrapAll(e):t.append(e)}))},wrap:function(e){var t=y(e);return this.each((function(r){T(this).wrapAll(t?e.call(this,r):e)}))},unwrap:function(e){return this.parent(e).not("body").each((function(){T(this).replaceWith(this.childNodes)})),this}}),T.expr.pseudos.hidden=function(e){return!T.expr.pseudos.visible(e)},T.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},T.ajaxSettings.xhr=function(){try{return new n.XMLHttpRequest}catch(e){}};var qt={0:200,1223:204},zt=T.ajaxSettings.xhr();m.cors=!!zt&&"withCredentials"in zt,m.ajax=zt=!!zt,T.ajaxTransport((function(e){var t,r;if(m.cors||zt&&!e.crossDomain)return{send:function(i,o){var a,s=e.xhr();if(s.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(a in e.xhrFields)s[a]=e.xhrFields[a];for(a in e.mimeType&&s.overrideMimeType&&s.overrideMimeType(e.mimeType),e.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest"),i)s.setRequestHeader(a,i[a]);t=function(e){return function(){t&&(t=r=s.onload=s.onerror=s.onabort=s.ontimeout=s.onreadystatechange=null,"abort"===e?s.abort():"error"===e?"number"!=typeof s.status?o(0,"error"):o(s.status,s.statusText):o(qt[s.status]||s.status,s.statusText,"text"!==(s.responseType||"text")||"string"!=typeof s.responseText?{binary:s.response}:{text:s.responseText},s.getAllResponseHeaders()))}},s.onload=t(),r=s.onerror=s.ontimeout=t("error"),void 0!==s.onabort?s.onabort=r:s.onreadystatechange=function(){4===s.readyState&&n.setTimeout((function(){t&&r()}))},t=t("abort");try{s.send(e.hasContent&&e.data||null)}catch(e){if(t)throw e}},abort:function(){t&&t()}}})),T.ajaxPrefilter((function(e){e.crossDomain&&(e.contents.script=!1)})),T.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return T.globalEval(e),e}}}),T.ajaxPrefilter("script",(function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")})),T.ajaxTransport("script",(function(e){var t,r;if(e.crossDomain||e.scriptAttrs)return{send:function(n,i){t=T("