@bsv/message-box-client 2.0.1 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/mod.js +1 -0
- package/dist/cjs/mod.js.map +1 -1
- package/dist/cjs/package.json +5 -5
- package/dist/cjs/src/MessageBoxClient.js +94 -29
- package/dist/cjs/src/MessageBoxClient.js.map +1 -1
- package/dist/cjs/src/RemittanceAdapter.js +137 -0
- package/dist/cjs/src/RemittanceAdapter.js.map +1 -0
- package/dist/cjs/src/__tests/RemittanceAdapter.test.js +133 -0
- package/dist/cjs/src/__tests/RemittanceAdapter.test.js.map +1 -0
- package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
- package/dist/esm/mod.js +1 -0
- package/dist/esm/mod.js.map +1 -1
- package/dist/esm/src/MessageBoxClient.js +94 -29
- package/dist/esm/src/MessageBoxClient.js.map +1 -1
- package/dist/esm/src/RemittanceAdapter.js +133 -0
- package/dist/esm/src/RemittanceAdapter.js.map +1 -0
- package/dist/esm/src/__tests/RemittanceAdapter.test.js +131 -0
- package/dist/esm/src/__tests/RemittanceAdapter.test.js.map +1 -0
- package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
- package/dist/types/mod.d.ts +1 -0
- package/dist/types/mod.d.ts.map +1 -1
- package/dist/types/src/MessageBoxClient.d.ts +2 -0
- package/dist/types/src/MessageBoxClient.d.ts.map +1 -1
- package/dist/types/src/RemittanceAdapter.d.ts +103 -0
- package/dist/types/src/RemittanceAdapter.d.ts.map +1 -0
- package/dist/types/src/__tests/RemittanceAdapter.test.d.ts +2 -0
- package/dist/types/src/__tests/RemittanceAdapter.test.d.ts.map +1 -0
- package/dist/types/tsconfig.types.tsbuildinfo +1 -1
- package/dist/umd/bundle.js +1 -1
- package/mod.ts +1 -0
- package/package.json +5 -5
- package/src/MessageBoxClient.ts +102 -28
- package/src/RemittanceAdapter.ts +164 -0
- package/src/__tests/RemittanceAdapter.test.ts +153 -0
package/dist/umd/bundle.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.messageBoxClient=e():t.messageBoxClient=e()}(this,()=>(()=>{"use strict";var t={d:(e,i)=>{for(var r in i)t.o(i,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:i[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{MessageBoxClient:()=>Wn,PeerPayClient:()=>Yn,STANDARD_PAYMENT_MESSAGEBOX:()=>Xn});var i={};t.r(i),t.d(i,{Decoder:()=>Cn,Encoder:()=>On,PacketType:()=>Nn,protocol:()=>An});const r="undefined"!=typeof globalThis?globalThis.Buffer:void 0,s=null!=r&&"function"==typeof r.from,n=new Int8Array(256).fill(-1);for(let t=0;t<10;t++)n[48+t]=t;for(let t=0;t<6;t++)n[65+t]=10+t,n[97+t]=10+t;class a{static zeros=["","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"];static groupSizes=[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];static groupBases=[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];static wordSize=26;static WORD_SIZE_BIGINT=BigInt(a.wordSize);static WORD_MASK=(1n<<a.WORD_SIZE_BIGINT)-1n;static MAX_SAFE_INTEGER_BIGINT=BigInt(Number.MAX_SAFE_INTEGER);static MIN_SAFE_INTEGER_BIGINT=BigInt(Number.MIN_SAFE_INTEGER);static MAX_IMULN_ARG=67108863;static MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT=(1n<<53n)-1n;_magnitude;_sign;_nominalWordLength;red;get negative(){return this._sign}set negative(t){this.assert(0===t||1===t,"Negative property must be 0 or 1");const e=1===t?1:0;0n===this._magnitude?this._sign=0:this._sign=e}get _computedWordsArray(){if(0n===this._magnitude)return[0];const t=[];let e=this._magnitude;for(;e>0n;)t.push(Number(e&a.WORD_MASK)),e>>=a.WORD_SIZE_BIGINT;return t.length>0?t:[0]}get words(){const t=this._computedWordsArray;if(this._nominalWordLength<=t.length)return t;const e=new Array(this._nominalWordLength).fill(0);for(let i=0;i<t.length;i++)e[i]=t[i];return e}set words(t){const e=this._sign;let i=0n;const r=t.length>0?t.length:1;for(let e=r-1;e>=0;e--){const r=void 0===t[e]?0:t[e];i=i<<a.WORD_SIZE_BIGINT|BigInt(r&Number(a.WORD_MASK))}this._magnitude=i,this._sign=e,this._nominalWordLength=r,this.normSign()}get length(){return Math.max(1,this._nominalWordLength)}static isBN(t){return t instanceof a||null!==t&&"object"==typeof t&&t.constructor?.wordSize===a.wordSize&&Array.isArray(t.words)}static max(t,e){return t.cmp(e)>0?t:e}static min(t,e){return t.cmp(e)<0?t:e}constructor(t=0,e=10,i="be"){if(this._magnitude=0n,this._sign=0,this._nominalWordLength=1,this.red=null,void 0===t&&(t=0),null===t)return void this._initializeState(0n,0);if("bigint"==typeof t)return this._initializeState(t<0n?-t:t,t<0n?1:0),void this.normSign();let r=e,s=i;if("le"!==e&&"be"!==e||(s=e,r=10),"number"!=typeof t)if(Array.isArray(t))this.initArray(t,s);else if("string"==typeof t){"hex"===r&&(r=16),this.assert("number"==typeof r&&r===(0|r)&&r>=2&&r<=36,"Base must be an integer between 2 and 36");const e=t.toString().replace(/\s+/g,"");let i=0,n=0;e.startsWith("-")?(i++,n=1):e.startsWith("+")&&i++;const a=e.substring(i);if(0===a.length)return this._initializeState(0n,1===n&&e.startsWith("-")?1:0),void this.normSign();if(16===r){let t;if("le"===s){const t=[];let e=a;e.length%2!=0&&(e="0"+e);for(let i=0;i<e.length;i+=2){const r=e.substring(i,i+2),s=parseInt(r,16);if(isNaN(s))throw new Error("Invalid character in "+e);t.push(s)}return this.initArray(t,"le"),this._sign=n,void this.normSign()}try{t=BigInt("0x"+a)}catch(t){throw new Error("Invalid character in "+a)}this._initializeState(t,n),this.normSign()}else try{if(this._parseBaseString(a,r),this._sign=n,this.normSign(),"le"===s){const t=this._sign;this.initArray(this.toArray("be"),"le"),this._sign=t,this.normSign()}}catch(t){const e=t;if(e.message.includes("Invalid character in string")||e.message.includes("Invalid digit for base")||e.message.startsWith("Invalid character:"))throw new Error("Invalid character");throw e}}else 0!==t?this.assert(!1,"Unsupported input type for BigNumber constructor"):this._initializeState(0n,0);else this.initNumber(t,s)}_bigIntToStringInBase(t,e){if(0n===t)return"0";if(e<2||e>36)throw new Error("Base must be between 2 and 36");let i="",r=t>0n?t:-t;const s=BigInt(e);for(;r>0n;)i="0123456789abcdefghijklmnopqrstuvwxyz"[Number(r%s)]+i,r/=s;return i}_parseBaseString(t,e){if(0===t.length)return this._magnitude=0n,void this._finishInitialization();this._magnitude=0n;const i=BigInt(e);let r=a.groupSizes[e],s=BigInt(a.groupBases[e]);0!==r&&0n!==s||(r=Math.floor(Math.log(67108863)/Math.log(e)),0===r&&(r=1),s=i**BigInt(r));let n=0;const o=t.length;let c=o%r;if(0===c&&o>0&&(c=r),c>0){const i=t.substring(n,n+c);this._magnitude=BigInt(this._parseBaseWord(i,e)),n+=c}for(;n<o;){const i=t.substring(n,n+r),a=BigInt(this._parseBaseWord(i,e));this._magnitude=this._magnitude*s+a,n+=r}this._finishInitialization()}_parseBaseWord(t,e){let i=0;for(let r=0;r<t.length;r++){const s=t.charCodeAt(r);let n;if(s>=48&&s<=57)n=s-48;else if(s>=65&&s<=90)n=s-65+10;else{if(!(s>=97&&s<=122))throw new Error("Invalid character: "+t[r]);n=s-97+10}if(n>=e)throw new Error("Invalid character");i=i*e+n}return i}_initializeState(t,e){this._magnitude=t,this._sign=0n===t?0:e,this._finishInitialization()}_finishInitialization(){if(0n===this._magnitude)this._nominalWordLength=1,this._sign=0;else{const t=this._magnitude.toString(2).length;this._nominalWordLength=Math.max(1,Math.ceil(t/a.wordSize))}}assert(t,e="Assertion failed"){if(!t)throw new Error(e)}initNumber(t,e="be"){if(this.assert(BigInt(Math.abs(t))<=a.MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT,"The number is larger than 2 ^ 53 (unsafe)"),this.assert(t%1==0,"Number must be an integer for BigNumber conversion"),this._initializeState(BigInt(Math.abs(t)),t<0?1:0),"le"===e){const t=this._sign,e=this.toArray("be");this.initArray(e,"le"),this._sign=t,this.normSign()}return this}initArray(t,e){if(0===t.length)return this._initializeState(0n,0),this;let i=0n;if("be"===e)for(let e=0;e<t.length;e++)i=i<<8n|BigInt(255&t[e]);else for(let e=t.length-1;e>=0;e--)i=i<<8n|BigInt(255&t[e]);return this._initializeState(i,0),this}copy(t){t._magnitude=this._magnitude,t._sign=this._sign,t._nominalWordLength=this._nominalWordLength,t.red=this.red}static move(t,e){t._magnitude=e._magnitude,t._sign=e._sign,t._nominalWordLength=e._nominalWordLength,t.red=e.red}clone(){const t=new a(0n);return this.copy(t),t}expand(t){return this.assert(t>=0,"Expand size must be non-negative"),this._nominalWordLength=Math.max(this._nominalWordLength,t,1),this}strip(){return this._finishInitialization(),this.normSign()}normSign(){return 0n===this._magnitude&&(this._sign=0),this}inspect(){return(null!==this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}_getMinimalHex(){return 0n===this._magnitude?"0":this._magnitude.toString(16)}toString(t=10,e=1){if(16===t||"hex"===t){let t=this._getMinimalHex();if(e>1)for("0"!==t&&t.length%2!=0&&(t="0"+t);t.length%e!==0;)t="0"+t;return(this.isNeg()?"-":"")+t}if("number"!=typeof t||t<2||t>36||t%1!=0)throw new Error("Base should be an integer between 2 and 36");return this.toBaseString(t,e)}toBaseString(t,e){if(0n===this._magnitude){let t="0";if(e>1)for(;t.length<e;)t="0"+t;return t}let i=a.groupSizes[t],r=BigInt(a.groupBases[t]);0!==i&&0n!==r||(i=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(t)),0===i&&(i=1),r=BigInt(t)**BigInt(i));let s="",n=this._magnitude;for(;n>0n;){const e=n%r;n/=r;const o=this._bigIntToStringInBase(e,t);if(n>0n){const t=i-o.length;s=t>0&&t<a.zeros.length?a.zeros[t]+o+s:t>0?"0".repeat(t)+o+s:o+s}else s=o+s}if(e>0)for(;s.length<e;)s="0"+s;return(1===this._sign?"-":"")+s}toNumber(){const t=this._getSignedValue();if(t>a.MAX_SAFE_INTEGER_BIGINT||t<a.MIN_SAFE_INTEGER_BIGINT)throw new Error("Number can only safely store up to 53 bits");return Number(t)}toBigInt(){return this._getSignedValue()}toJSON(){const t=this._getMinimalHex();return(this.isNeg()?"-":"")+t}toArrayLikeGeneric(t,e){let i=this._magnitude,r=e?0:t.length-1;const s=e?1:-1;for(let e=0;e<t.length;++e){if(0n===i&&r>=0&&r<t.length)t[r]=0;else{if(!(r>=0&&r<t.length))break;t[r]=Number(0xffn&i)}i>>=8n,r+=s}}toArray(t="be",e){this.strip();const i=this.byteLength(),r=e??Math.max(1,i);this.assert(i<=r,"byte array longer than desired length"),this.assert(r>0,"Requested array length <= 0");const s=new Array(r).fill(0);return 0n===this._magnitude&&r>0?s:0n===this._magnitude&&0===r?[]:(this.toArrayLikeGeneric(s,"le"===t),s)}bitLength(){return 0n===this._magnitude?0:this._magnitude.toString(2).length}static toBitArray(t){const e=t.bitLength();if(0===e)return[];const i=new Array(e),r=t._magnitude;for(let t=0;t<e;t++)i[t]=0n!=(r>>BigInt(t)&1n)?1:0;return i}toBitArray(){return a.toBitArray(this)}zeroBits(){if(0n===this._magnitude)return 0;let t=0,e=this._magnitude;for(;0n==(1n&e)&&0n!==e;)t++,e>>=1n;return t}byteLength(){return 0n===this._magnitude?0:Math.ceil(this.bitLength()/8)}_getSignedValue(){return 1===this._sign?-this._magnitude:this._magnitude}_setValueFromSigned(t){t<0n?(this._magnitude=-t,this._sign=1):(this._magnitude=t,this._sign=0),this._finishInitialization(),this.normSign()}toTwos(t){this.assert(t>=0);const e=BigInt(t);let i=this._getSignedValue();1===this._sign&&0n!==this._magnitude&&(i=(1n<<e)+i),i&=(1n<<e)-1n;const r=new a(0n);return r._initializeState(i,0),r}fromTwos(t){this.assert(t>=0);const e=BigInt(t),i=this._magnitude;if(t>0&&0n!=(i>>e-1n&1n)&&0===this._sign){const t=i-(1n<<e),r=new a(0n);return r._setValueFromSigned(t),r}return this.clone()}isNeg(){return 1===this._sign&&0n!==this._magnitude}neg(){return this.clone().ineg()}ineg(){return 0n!==this._magnitude&&(this._sign=1===this._sign?0:1),this}_iuop(t,e){const i=e(this._magnitude,t._magnitude),r=e===((t,e)=>t^e);let s=this._nominalWordLength;return r&&(s=Math.max(this.length,t.length)),this._magnitude=i,this._finishInitialization(),r&&(this._nominalWordLength=Math.max(this._nominalWordLength,s)),this.strip()}iuor(t){return this._iuop(t,(t,e)=>t|e)}iuand(t){return this._iuop(t,(t,e)=>t&e)}iuxor(t){return this._iuop(t,(t,e)=>t^e)}_iop(t,e){return this.assert(0===this._sign&&0===t._sign),this._iuop(t,e)}ior(t){return this._iop(t,(t,e)=>t|e)}iand(t){return this._iop(t,(t,e)=>t&e)}ixor(t){return this._iop(t,(t,e)=>t^e)}_uop_new(t,e){return this.length>=t.length?this.clone()[e](t):t.clone()[e](this)}or(t){return this.assert(0===this._sign&&0===t._sign),this._uop_new(t,"iuor")}uor(t){return this._uop_new(t,"iuor")}and(t){return this.assert(0===this._sign&&0===t._sign),this._uop_new(t,"iuand")}uand(t){return this._uop_new(t,"iuand")}xor(t){return this.assert(0===this._sign&&0===t._sign),this._uop_new(t,"iuxor")}uxor(t){return this._uop_new(t,"iuxor")}inotn(t){this.assert("number"==typeof t&&t>=0);const e=(1n<<BigInt(t))-1n;this._magnitude=~this._magnitude&e;const i=0===t?1:Math.ceil(t/a.wordSize);return this._nominalWordLength=Math.max(1,i),this.strip(),this._nominalWordLength=Math.max(this._nominalWordLength,Math.max(1,i)),this}notn(t){return this.clone().inotn(t)}setn(t,e){this.assert("number"==typeof t&&t>=0);const i=BigInt(t);1===e||!0===e?this._magnitude|=1n<<i:this._magnitude&=~(1n<<i);const r=Math.floor(t/a.wordSize)+1;return this._nominalWordLength=Math.max(this._nominalWordLength,r),this._finishInitialization(),this.strip()}iadd(t){return this._setValueFromSigned(this._getSignedValue()+t._getSignedValue()),this}add(t){const e=new a(0n);return e._setValueFromSigned(this._getSignedValue()+t._getSignedValue()),e}isub(t){return this._setValueFromSigned(this._getSignedValue()-t._getSignedValue()),this}sub(t){const e=new a(0n);return e._setValueFromSigned(this._getSignedValue()-t._getSignedValue()),e}mul(t){const e=new a(0n);return e._magnitude=this._magnitude*t._magnitude,e._sign=0n===e._magnitude?0:this._sign^t._sign,e._nominalWordLength=this.length+t.length,e.red=null,e.normSign()}imul(t){return this._magnitude*=t._magnitude,this._sign=0n===this._magnitude?0:this._sign^t._sign,this._nominalWordLength=this.length+t.length,this.red=null,this.normSign()}imuln(t){return this.assert("number"==typeof t,"Assertion failed"),this.assert(Math.abs(t)<=a.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()*BigInt(t)),this}muln(t){return this.clone().imuln(t)}sqr(){const t=new a(0n);return t._magnitude=this._magnitude*this._magnitude,t._sign=0,t._nominalWordLength=2*this.length,t.red=null,t}isqr(){return this._magnitude*=this._magnitude,this._sign=0,this._nominalWordLength=2*this.length,this.red=null,this}pow(t){if(this.assert(0===t._sign,"Exponent for pow must be non-negative"),t.isZero())return new a(1n);const e=new a(1n),i=this.clone(),r=t.clone(),s=i.isNeg(),n=r.isOdd();for(s&&i.ineg();!r.isZero();)r.isOdd()&&e.imul(i),i.isqr(),r.iushrn(1);return s&&n&&e.ineg(),e}static normalizeNonNegativeBigInt(t,e){if("number"==typeof t){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return BigInt(t)}if(t<0n)throw new Error(`${e} must be a non-negative integer`);return t}iushln(t){const e=a.normalizeNonNegativeBigInt(t,"Shift bits");return 0n===e?this:(this._magnitude<<=e,this._finishInitialization(),this.strip())}ishln(t){return this.assert(0===this._sign,"ishln requires positive number"),this.iushln(t)}iushrn(t,e,i){const r=a.normalizeNonNegativeBigInt(t,"Shift bits");if(0n===r)return null!=i&&i._initializeState(0n,0),this;if(null!=i){const t=(1n<<r)-1n,e=this._magnitude&t;i._initializeState(e,0)}return this._magnitude>>=r,this._finishInitialization(),this.strip()}ishrn(t,e,i){return this.assert(0===this._sign,"ishrn requires positive number"),this.iushrn(t,e,i)}shln(t){return this.clone().ishln(t)}ushln(t){return this.clone().iushln(t)}shrn(t){return this.clone().ishrn(t)}ushrn(t){return this.clone().iushrn(t)}testn(t){return this.assert("number"==typeof t&&t>=0),0n!=(this._magnitude>>BigInt(t)&1n)}imaskn(t){this.assert("number"==typeof t&&t>=0),this.assert(0===this._sign,"imaskn works only with positive numbers");const e=BigInt(t),i=0n===e?0n:(1n<<e)-1n;this._magnitude&=i;const r=0===t?1:Math.max(1,Math.ceil(t/a.wordSize));return this._nominalWordLength=r,this._finishInitialization(),this._nominalWordLength=Math.max(this._nominalWordLength,r),this.strip()}maskn(t){return this.clone().imaskn(t)}iaddn(t){return this.assert("number"==typeof t),this.assert(Math.abs(t)<=a.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()+BigInt(t)),this}_iaddn(t){return this.iaddn(t)}isubn(t){return this.assert("number"==typeof t),this.assert(Math.abs(t)<=a.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()-BigInt(t)),this}addn(t){return this.clone().iaddn(t)}subn(t){return this.clone().isubn(t)}iabs(){return this._sign=0,this}abs(){return this.clone().iabs()}divmod(t,e,i){if(this.assert(!t.isZero(),"Division by zero"),this.isZero()){const t=new a(0n);return{div:"mod"!==e?t:null,mod:"div"!==e?t:null}}const r=this._getSignedValue(),s=t._getSignedValue();let n=null,o=null;"mod"!==e&&(n=r/s),"div"!==e&&(o=r%s,!0===i&&o<0n&&(o+=s<0n?-s:s));const c=null!==n?new a(0n):null;null!==c&&null!==n&&c._setValueFromSigned(n);const h=null!==o?new a(0n):null;return null!==h&&null!==o&&h._setValueFromSigned(o),{div:c,mod:h}}div(t){return this.divmod(t,"div",!1).div}mod(t){return this.divmod(t,"mod",!1).mod}umod(t){return this.divmod(t,"mod",!0).mod}divRound(t){this.assert(!t.isZero());const e=this._getSignedValue(),i=t._getSignedValue();let r=e/i;const s=e%i;if(0n===s){const t=new a(0n);return t._setValueFromSigned(r),t}2n*(s<0n?-s:s)>=(i<0n?-i:i)&&(e>0n&&i>0n||e<0n&&i<0n?r+=1n:r-=1n);const n=new a(0n);return n._setValueFromSigned(r),n}modrn(t){this.assert(0!==t,"Division by zero in modrn");const e=BigInt(Math.abs(t));if(0n===e)throw new Error("Division by zero in modrn");const i=this._magnitude%e;return Number(t<0?-i:i)}idivn(t){return this.assert(0!==t),this.assert(Math.abs(t)<=a.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()/BigInt(t)),this}divn(t){return this.clone().idivn(t)}egcd(t){this.assert(0===t._sign,"p must not be negative"),this.assert(!t.isZero(),"p must not be zero");let e=this._getSignedValue(),i=t._magnitude,r=1n,s=0n,n=0n,o=1n;for(;0n!==i;){const t=e/i;let a=i;i=e%i,e=a,a=s,s=r-t*s,r=a,a=o,o=n-t*o,n=a}const c=new a(0n);c._setValueFromSigned(r);const h=new a(0n);h._setValueFromSigned(n);const u=new a(0n);return u._initializeState(e<0n?-e:e,0),{a:c,b:h,gcd:u}}gcd(t){let e=this._magnitude,i=t._magnitude;if(0n===e){const t=new a(0n);return t._setValueFromSigned(i),t.iabs()}if(0n===i){const t=new a(0n);return t._setValueFromSigned(e),t.iabs()}for(;0n!==i;){const t=e%i;e=i,i=t}const r=new a(0n);return r._initializeState(e,0),r}invm(t){this.assert(!t.isZero()&&0===t._sign,"Modulus for invm must be positive and non-zero");const e=this.egcd(t);if(!e.gcd.eqn(1))throw new Error("Inverse does not exist (numbers are not coprime).");return e.a.umod(t)}isEven(){return this._magnitude%2n==0n}isOdd(){return this._magnitude%2n==1n}andln(t){return this.assert(t>=0),Number(this._magnitude&BigInt(t))}bincn(t){this.assert("number"==typeof t&&t>=0);const e=1n<<BigInt(t);return this._setValueFromSigned(this._getSignedValue()+e),this}isZero(){return 0n===this._magnitude}cmpn(t){this.assert(Math.abs(t)<=a.MAX_IMULN_ARG,"Number is too big");const e=this._getSignedValue(),i=BigInt(t);return e<i?-1:e>i?1:0}cmp(t){const e=this._getSignedValue(),i=t._getSignedValue();return e<i?-1:e>i?1:0}ucmp(t){return this._magnitude<t._magnitude?-1:this._magnitude>t._magnitude?1:0}gtn(t){return 1===this.cmpn(t)}gt(t){return 1===this.cmp(t)}gten(t){return this.cmpn(t)>=0}gte(t){return this.cmp(t)>=0}ltn(t){return-1===this.cmpn(t)}lt(t){return-1===this.cmp(t)}lten(t){return this.cmpn(t)<=0}lte(t){return this.cmp(t)<=0}eqn(t){return 0===this.cmpn(t)}eq(t){return 0===this.cmp(t)}toRed(t){return this.assert(null==this.red,"Already a number in reduction context"),this.assert(0===this._sign,"toRed works only with positives"),t.convertTo(this).forceRed(t)}fromRed(){return this.assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(t){return this.red=t,this}redAdd(t){return this.assert(this.red,"redAdd works only with red numbers"),this.red.add(this,t)}redIAdd(t){return this.assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)}redSub(t){return this.assert(this.red,"redSub works only with red numbers"),this.red.sub(this,t)}redISub(t){return this.assert(this.red,"redISub works only with red numbers"),this.red.isub(this,t)}redShl(t){return this.assert(this.red,"redShl works only with red numbers"),this.red.shl(this,t)}redMul(t){return this.assert(this.red,"redMul works only with red numbers"),this.red.verify2(this,t),this.red.mul(this,t)}redIMul(t){return this.assert(this.red,"redIMul works only with red numbers"),this.red.verify2(this,t),this.red.imul(this,t)}redSqr(){return this.assert(this.red,"redSqr works only with red numbers"),this.red.verify1(this),this.red.sqr(this)}redISqr(){return this.assert(this.red,"redISqr works only with red numbers"),this.red.verify1(this),this.red.isqr(this)}redSqrt(){return this.assert(this.red,"redSqrt works only with red numbers"),this.red.verify1(this),this.red.sqrt(this)}redInvm(){return this.assert(this.red,"redInvm works only with red numbers"),this.red.verify1(this),this.red.invm(this)}redNeg(){return this.assert(this.red,"redNeg works only with red numbers"),this.red.verify1(this),this.red.neg(this)}redPow(t){return this.assert(null!=this.red&&null==t.red,"redPow(normalNum)"),this.red.verify1(this),this.red.pow(this,t)}static fromHex(t,e){let i="be";return"little"!==e&&"le"!==e||(i="le"),new a(t,16,i)}toHex(t=0){if(this.isZero()&&0===t)return"";let e=this._getMinimalHex();"0"!==e&&e.length%2!=0&&(e="0"+e);const i=2*t;for(;e.length<i;)e="0"+e;return(this.isNeg()?"-":"")+e}static fromJSON(t){return new a(t,16)}static fromNumber(t){return new a(t)}static fromString(t,e){return new a(t,e)}static fromSm(t,e="big"){if(0===t.length)return new a(0n);const i=t.slice();"little"===e&&i.reverse();let n=0;i.length>0&&128&i[0]&&(n=1,i[0]&=127);let o=0n;if(s){const t=r.from(i).toString("hex");o=0===t.length?0n:BigInt("0x"+t)}else{let t="";for(const e of i)t+=e<16?"0"+e.toString(16):e.toString(16);o=0===t.length?0n:BigInt("0x"+t)}const c=new a(0n);return c._initializeState(o,n),c}toSm(t="big"){if(0n===this._magnitude)return 1===this._sign?[128]:[];let e=this._getMinimalHex();e.length%2!=0&&(e="0"+e);const i=e.length/2,r=new Array(i);for(let t=0,i=0;t<e.length;t+=2){const s=n[e.charCodeAt(t)],a=n[e.charCodeAt(t+1)];r[i++]=(15&s)<<4|15&a}let s;return 1===this._sign?128&r[0]?s=[128,...r]:(s=r.slice(),s[0]|=128):s=128&r[0]?[0,...r]:r.slice(),"little"===t?s.reverse():s}static fromBits(t,e=!1){const i=t>>>24,r=8388607&t,s=!!(8388608&t);if(e&&s)throw new Error("negative bit set");if(0===i&&0===r){if(s&&e)throw new Error("negative bit set for zero value");return new a(0n)}const n=new a(r);return i<=3?n.iushrn(8*(3-i)):n.iushln(8*(i-3)),s&&n.ineg(),n}toBits(){if(this.strip(),this.isZero()&&!this.isNeg())return 0;const t=this.isNeg(),e=this.abs();let i=e.toArray("be"),r=0;for(;r<i.length-1&&0===i[r];)r++;i=i.slice(r);let s,n=i.length;if(0!==n||e.isZero()||(i=[0],n=1),e.isZero()&&(n=0,i=[]),0===n)s=0;else if(n<=3){s=0;for(let t=0;t<n;t++)s=s<<8|i[t]}else s=i[0]<<16|i[1]<<8|i[2];8388608&s&&n<=255&&(s>>>=8,n++);let a=n<<24|s;return t&&(a|=8388608),a>>>0}static fromScriptNum(t,e=!1,i){if(void 0!==i&&t.length>i)throw new Error("script number overflow");if(0===t.length)return new a(0n);if(e&&!(127&t[t.length-1]||!(t.length<=1)&&128&t[t.length-2]))throw new Error("non-minimally encoded script number");return a.fromSm(t,"little")}toScriptNum(){return this.toSm("little")}_invmp(t){this.assert(0===t._sign,"p must not be negative for _invmp"),this.assert(!t.isZero(),"p must not be zero for _invmp");const e=this.umod(t),i=t.subn(2);if(null!==e.red)return e.redPow(i);let r=new a(1n),s=e.clone();const n=i.clone();for(;!n.isZero();)n.isOdd()&&(r=r.mul(s).umod(t)),s=s.sqr().umod(t),n.iushrn(1);return r}mulTo(t,e){return e._magnitude=this._magnitude*t._magnitude,e._sign=0n===e._magnitude?0:this._sign^t._sign,e._nominalWordLength=this.length+t.length,e.red=null,e.normSign(),e}}class o{name;p;k;n;tmp;constructor(t,e){this.name=t,this.p=new a(e,16),this.n=this.p.bitLength(),this.k=new a(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){const t=new a(BigInt(0)),e=Math.ceil(this.n/a.wordSize);return t.expand(Math.max(1,e)),t}ireduce(t){const e=t;let i;do{this.split(e,this.tmp),this.imulK(e),e.iadd(this.tmp),i=e.bitLength()}while(i>this.n);const r=i<this.n?-1:e.ucmp(this.p);return 0===r?e.words=[0]:r>0&&e.isub(this.p),e.strip(),e}split(t,e){t.iushrn(this.n,0,e)}imulK(t){return t.imul(this.k)}}class c extends o{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(t,e){const i=4194303,r=t.words,s=t.length,n=Math.min(s,9),a=new Array(n+(s>9?1:0)).fill(0);for(let t=0;t<n;t++)a[t]=r[t];let o=n;if(s<=9){const i=new Array(o);for(let t=0;t<o;++t)i[t]=a[t];return e.words=i,void(t.words=[0])}let c=r[9];a[o++]=c&i;const h=new Array(o);for(let t=0;t<o;++t)h[t]=a[t];e.words=h;const u=new Array(Math.max(1,s-9)).fill(0);let d=0;for(let t=10;t<s;t++){const e=0|r[t];d<u.length&&(u[d++]=(e&i)<<4|c>>>22),c=e}c>>>=22,d<u.length?u[d++]=c:0!==c&&u.length;const l=new Array(d);for(let t=0;t<d;++t)l[t]=u[t];t.words=l}imulK(t){const e=t.words,i=t.length,r=i+2,s=new Array(r).fill(0);for(let t=0;t<i;t++)s[t]=e[t];let n=0;for(let t=0;t<r;t++){const e=0|s[t];n+=977*e,s[t]=67108863&n,n=64*e+(n/67108864|0)}return t.words=s,t}}class h{prime;m;constructor(t){if("k256"===t){const t=new c;this.m=t.p,this.prime=t}else this.assert(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}assert(t,e="Assertion failed"){if(!t)throw new Error(e)}verify1(t){this.assert(0===t.negative,"red works only with positives"),this.assert(t.red,"red works only with red numbers")}verify2(t,e){this.assert(0===(t.negative|e.negative),"red works only with positives"),this.assert(null!=t.red&&t.red===e.red,"red works only with red numbers")}imod(t){return null!=this.prime?this.prime.ireduce(t).forceRed(this):(a.move(t,t.umod(this.m).forceRed(this)),t)}neg(t){return t.isZero()?t.clone():this.m.sub(t).forceRed(this)}add(t,e){this.verify2(t,e);const i=t.clone();return i.iadd(e),i.isub(this.m),i.isNeg()&&i.iadd(this.m),i}iadd(t,e){return this.verify2(t,e),t.iadd(e),t.isub(this.m),t.isNeg()&&t.iadd(this.m),t}sub(t,e){this.verify2(t,e);const i=t.sub(e);return i.cmpn(0)<0&&i.iadd(this.m),i.forceRed(this)}isub(t,e){this.verify2(t,e);const i=t.isub(e);return i.cmpn(0)<0&&i.iadd(this.m),i}shl(t,e){return this.verify1(t),this.imod(t.ushln(e))}imul(t,e){return this.verify2(t,e),this.imod(t.imul(e))}mul(t,e){return this.verify2(t,e),this.imod(t.mul(e))}isqr(t){return this.imul(t,t.clone())}sqr(t){return this.mul(t,t)}sqrt(t){if(t.isZero())return t.clone();const e=this.m.andln(3);if(this.assert(e%2==1),3===e){const e=this.m.add(new a(1)).iushrn(2);return this.pow(t,e)}const i=this.m.subn(1);let r=0;for(;!i.isZero()&&0===i.andln(1);)r++,i.iushrn(1);this.assert(!i.isZero());const s=new a(1).toRed(this),n=s.redNeg(),o=this.m.subn(1).iushrn(1),c=this.m.bitLength(),h=new a(2*c*c).toRed(this);for(;0!==this.pow(h,o).cmp(n);)h.redIAdd(n);let u=this.pow(h,i),d=this.pow(t,i.addn(1).iushrn(1)),l=this.pow(t,i),f=r;for(;0!==l.cmp(s);){let t=l,e=0;for(;0!==t.cmp(s);e++)t=t.redSqr();this.assert(e<f);const i=this.pow(u,new a(1).iushln(f-e-1));d=d.redMul(i),u=i.redSqr(),l=l.redMul(u),f=e}return d}invm(t){const e=t._invmp(this.m);return 0!==e.negative?(e.negative=0,this.imod(e).redNeg()):this.imod(e)}pow(t,e){if(this.verify1(t),e.isZero())return new a(1).toRed(this);let i=new a(1).toRed(this);const r=t.clone();for(let t=e.bitLength()-1;t>=0;t--)i=this.sqr(i),e.testn(t)&&(i=this.mul(i,r));return i}convertTo(t){const e=t.umod(this.m);return e===t?e.clone():e}convertFrom(t){const e=t.clone();return e.red=null,e}}class u extends h{shift;r;r2;rinv;minv;constructor(t){super(t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new a(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)}convertTo(t){return this.imod(t.ushln(this.shift))}convertFrom(t){const e=this.imod(t.mul(this.rinv));return e.red=null,e}imul(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;const i=t.imul(e),r=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),s=i.isub(r).iushrn(this.shift);let n=s;return s.cmp(this.m)>=0?n=s.isub(this.m):s.cmpn(0)<0&&(n=s.iadd(this.m)),n.forceRed(this)}mul(t,e){if(t.isZero()||e.isZero())return new a(0).forceRed(this);const i=t.mul(e),r=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),s=i.isub(r).iushrn(this.shift);let n=s;return s.cmp(this.m)>=0?n=s.isub(this.m):s.cmpn(0)<0&&(n=s.iadd(this.m)),n.forceRed(this)}invm(t){return this.imod(t._invmp(this.m).mul(this.r2)).forceRed(this)}}class d{curve;type;precomputed;constructor(t){this.curve=new Re,this.type=t,this.precomputed=null}}class l extends d{x;y;z;zOne;constructor(t,e,i){super("jacobian"),null===t&&null===e&&null===i?(this.x=this.curve.one,this.y=this.curve.one,this.z=new a(0)):(a.isBN(t)||(t=new a(t,16)),this.x=t,a.isBN(e)||(e=new a(e,16)),this.y=e,a.isBN(i)||(i=new a(i,16)),this.z=i),null==this.x.red&&(this.x=this.x.toRed(this.curve.red)),null==this.y.red&&(this.y=this.y.toRed(this.curve.red)),null==this.z.red&&(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.isInfinity()&&(this.x=this.curve.one,this.y=this.curve.one,this.z=new a(0).toRed(this.curve.red),this.zOne=!1)}toP(){if(this.isInfinity())return new Te(null,null);const t=this.z.redInvm(),e=t.redSqr(),i=this.x.redMul(e),r=this.y.redMul(e).redMul(t);return new Te(i,r)}neg(){return new l(this.x,this.y.redNeg(),this.z)}add(t){if(this.isInfinity())return t;if(t.isInfinity())return this;const e=t.z.redSqr(),i=this.z.redSqr(),r=this.x.redMul(e),s=t.x.redMul(i),n=this.y.redMul(e.redMul(t.z)),a=t.y.redMul(i.redMul(this.z)),o=r.redSub(s),c=n.redSub(a);if(0===o.cmpn(0))return 0!==c.cmpn(0)?new l(null,null,null):this.dbl();const h=o.redSqr(),u=h.redMul(o),d=r.redMul(h),f=c.redSqr().redIAdd(u).redISub(d).redISub(d),p=c.redMul(d.redISub(f)).redISub(n.redMul(u)),g=this.z.redMul(t.z).redMul(o);return new l(f,p,g)}mixedAdd(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;if(null===t.x||null===t.y)throw new Error("Point coordinates cannot be null");const e=this.z.redSqr(),i=this.x,r=t.x.redMul(e),s=this.y,n=t.y.redMul(e).redMul(this.z),a=i.redSub(r),o=s.redSub(n);if(0===a.cmpn(0))return 0!==o.cmpn(0)?new l(null,null,null):this.dbl();const c=a.redSqr(),h=c.redMul(a),u=i.redMul(c),d=o.redSqr().redIAdd(h).redISub(u).redISub(u),f=o.redMul(u.redISub(d)).redISub(s.redMul(h)),p=this.z.redMul(a);return new l(d,f,p)}dblp(t){if(0===t)return this;if(this.isInfinity())return this;if(void 0===t)return this.dbl();let e=this;for(let i=0;i<t;i++)e=e.dbl();return e}dbl(){if(this.isInfinity())return this;let t,e,i;if(this.zOne){const r=this.x.redSqr(),s=this.y.redSqr(),n=s.redSqr();let a=this.x.redAdd(s).redSqr().redISub(r).redISub(n);a=a.redIAdd(a);const o=r.redAdd(r).redIAdd(r),c=o.redSqr().redISub(a).redISub(a);let h=n.redIAdd(n);h=h.redIAdd(h),h=h.redIAdd(h),t=c,e=o.redMul(a.redISub(c)).redISub(h),i=this.y.redAdd(this.y)}else{const r=this.x.redSqr(),s=this.y.redSqr(),n=s.redSqr();let a=this.x.redAdd(s).redSqr().redISub(r).redISub(n);a=a.redIAdd(a);const o=r.redAdd(r).redIAdd(r),c=o.redSqr();let h=n.redIAdd(n);h=h.redIAdd(h),h=h.redIAdd(h),t=c.redISub(a).redISub(a),e=o.redMul(a.redISub(t)).redISub(h),i=this.y.redMul(this.z),i=i.redIAdd(i)}return new l(t,e,i)}eq(t){if("affine"===t.type)return this.eq(t.toJ());if(this===t)return!0;if(this.isInfinity()&&t.isInfinity())return!0;if(this.isInfinity()!==t.isInfinity())return!1;const e=this.z.redSqr(),i=t.z.redSqr();if(0!==this.x.redMul(i).redISub(t.x.redMul(e)).cmpn(0))return!1;const r=e.redMul(this.z),s=i.redMul(t.z);return 0===this.y.redMul(s).redISub(t.y.redMul(r)).cmpn(0)}eqXToP(t){const e=this.z.redSqr(),i=t.toRed(this.curve?.red).redMul(e);if(0===this.x.cmp(i))return!0;const r=t.clone();if(null===this.curve||null==this.curve.redN)throw new Error("Curve or redN is not initialized.");const s=this.curve.redN.redMul(e);for(;r.cmp(this.curve.p)<0;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(i.redIAdd(s),0===this.x.cmp(i))return!0}return!1}inspect(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"}isInfinity(){return 0===this.z.cmpn(0)}}const f=/^[0-9a-fA-F]*$/;function p(t){if("string"!=typeof t)throw new TypeError("Invalid hex string");if(0!==t.length&&!f.test(t))throw new Error("Invalid hex string")}const g=(t,e="Hash assertion failed")=>{if(!t)throw new Error(e)};class y{pending;pendingTotal;blockSize;outSize;endian;_delta8;_delta32;padLength;hmacStrength;constructor(t,e,i,r){this.pending=null,this.pendingTotal=0,this.blockSize=t,this.outSize=e,this.hmacStrength=i,this.padLength=r/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}_update(t,e){throw new Error("Not implemented")}_digest(){throw new Error("Not implemented")}_digestHex(){throw new Error("Not implemented")}update(t,e){if(t=m(t,e),null==this.pending?this.pending=t:this.pending=this.pending.concat(t),this.pendingTotal+=t.length,this.pending.length>=this._delta8){const e=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-e,t.length),0===this.pending.length&&(this.pending=null),t=function(t,e,i,r){const s=i-0;g(s%4==0);const n=new Array(s/4);for(let e=0,i=0;e<n.length;e++,i+=4){let s;s="big"===r?t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3]:t[i+3]<<24|t[i+2]<<16|t[i+1]<<8|t[i],n[e]=s>>>0}return n}(t,0,t.length-e,this.endian);for(let e=0;e<t.length;e+=this._delta32)this._update(t,e)}return this}digest(){return this.update(this._pad()),g(null===this.pending),this._digest()}digestHex(){return this.update(this._pad()),g(null===this.pending),this._digestHex()}_pad(){const t=this.pendingTotal;if(!Number.isSafeInteger(t)||t<0)throw new Error("Message too long for this hash function");const e=this._delta8,i=e-(t+this.padLength)%e,r=new Array(i+this.padLength);let s;for(r[0]=128,s=1;s<i;s++)r[s]=0;const n=this.padLength,a=1n<<BigInt(8*n);let o=8n*BigInt(t);if(o>=a)throw new Error("Message too long for this hash function");if("big"===this.endian){const t=new Array(n);for(let e=n-1;e>=0;e--)t[e]=Number(0xffn&o),o>>=8n;for(let e=0;e<n;e++)r[s++]=t[e]}else for(let t=0;t<n;t++)r[s++]=Number(0xffn&o),o>>=8n;return r}}function b(t,e){return 55296==(64512&t.charCodeAt(e))&&!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1))}function m(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];const i=[];if("string"==typeof t)if("hex"!==e){let e=0;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);s<128?i[e++]=s:s<2048?(i[e++]=s>>6|192,i[e++]=63&s|128):b(t,r)?(s=65536+((1023&s)<<10)+(1023&t.charCodeAt(++r)),i[e++]=s>>18|240,i[e++]=s>>12&63|128,i[e++]=s>>6&63|128,i[e++]=63&s|128):(i[e++]=s>>12|224,i[e++]=s>>6&63|128,i[e++]=63&s|128)}}else{p(t),t=function(t){if(p(t),0===t.length)return"";let e=t.toLowerCase();return e.length%2!=0&&(e="0"+e),e}(t);for(let e=0;e<t.length;e+=2)i.push(parseInt(t[e]+t[e+1],16))}else for(let e=0;e<t.length;e++)i[e]=0|t[e];return i}function w(t){return function(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}(t)}function v(t,e){let i="";for(let r=0;r<t.length;r++){let s=t[r];"little"===e&&(s=w(s)),i+=I(s.toString(16))}return i}function I(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}function k(t){let e="";for(const i of t)e+=i.toString(16).padStart(2,"0");return e}function S(t,e){const i=new Array(4*t.length);for(let r=0,s=0;r<t.length;r++,s+=4){const n=t[r];"big"===e?(i[s]=n>>>24,i[s+1]=n>>>16&255,i[s+2]=n>>>8&255,i[s+3]=255&n):(i[s+3]=n>>>24,i[s+2]=n>>>16&255,i[s+1]=n>>>8&255,i[s]=255&n)}return i}function E(t,e){return t>>>e|t<<32-e}function x(t,e){return t<<e|t>>>32-e}function _(t,e){return t+e>>>0}function P(t,e,i){return t+e+i>>>0}function A(t,e,i,r){return t+e+i+r>>>0}function N(t,e,i,r,s){return t+e+i+r+s>>>0}function O(t,e,i,r){return 0===t?T(e,i,r):1===t||3===t?function(t,e,i){return t^e^i}(e,i,r):2===t?C(e,i,r):0}function T(t,e,i){return t&e^~t&i}function C(t,e,i){return t&e^t&i^e&i}function R(t){return E(t,2)^E(t,13)^E(t,22)}function B(t){return E(t,6)^E(t,11)^E(t,25)}function L(t){return E(t,7)^E(t,18)^t>>>3}function M(t){return E(t,17)^E(t,19)^t>>>10}const F=[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],U=[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],D=[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],H=[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];function q(t,e,i,r){return t<=15?e^i^r:t<=31?e&i|~e&r:t<=47?(e|~i)^r:t<=63?e&r|i&~r:e^(i|~r)}function V(t){return t<=15?0:t<=31?1518500249:t<=47?1859775393:t<=63?2400959708:2840853838}function K(t){return t<=15?1352829926:t<=31?1548603684:t<=47?1836072691:t<=63?2053994217:0}class $ extends y{h;constructor(){super(512,160,192,64),this.endian="little",this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}_update(t,e){let i,r=this.h[0],s=this.h[1],n=this.h[2],a=this.h[3],o=this.h[4],c=r,h=s,u=n,d=a,l=o;for(let f=0;f<80;f++)i=_(x(A(r,q(f,s,n,a),t[F[f]+e],V(f)),D[f]),o),r=o,o=a,a=x(n,10),n=s,s=i,i=_(x(A(c,q(79-f,h,u,d),t[U[f]+e],K(f)),H[f]),l),c=l,l=d,d=x(u,10),u=h,h=i;i=P(this.h[1],n,d),this.h[1]=P(this.h[2],a,l),this.h[2]=P(this.h[3],o,c),this.h[3]=P(this.h[4],r,h),this.h[4]=P(this.h[0],s,u),this.h[0]=i}_digest(){return S(this.h,"little")}_digestHex(){return v(this.h,"little")}}class j{h;constructor(){this.h=new At}update(t,e){const i=t instanceof Uint8Array?t:Uint8Array.from(m(t,e));return this.h.update(i),this}digest(){return Array.from(this.h.digest())}digestHex(){return k(this.h.digest())}}class z extends y{h;W;k;constructor(){super(512,160,80,64),this.k=[1518500249,1859775393,2400959708,3395469782],this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}_update(t,e){const i=this.W;let r;for(void 0===e&&(e=0),r=0;r<16;r++)i[r]=t[e+r];for(;r<i.length;r++)i[r]=x(i[r-3]^i[r-8]^i[r-14]^i[r-16],1);let s=this.h[0],n=this.h[1],a=this.h[2],o=this.h[3],c=this.h[4];for(r=0;r<i.length;r++){const t=~~(r/20),e=N(x(s,5),O(t,n,a,o),c,i[r],this.k[t]);c=o,o=a,a=x(n,30),n=s,s=e}this.h[0]=_(this.h[0],s),this.h[1]=_(this.h[1],n),this.h[2]=_(this.h[2],a),this.h[3]=_(this.h[3],o),this.h[4]=_(this.h[4],c)}_digest(){return S(this.h,"big")}_digestHex(){return v(this.h,"big")}}class W{h;blockSize=64;outSize=32;constructor(t){const e=t instanceof Uint8Array?t:Uint8Array.from(m(t,"string"==typeof t?"hex":void 0));this.h=new Ut(Nt,e)}update(t,e){const i=t instanceof Uint8Array?t:Uint8Array.from(m(t,e));return this.h.update(i),this}digest(){return Array.from(this.h.digest())}digestHex(){return k(this.h.digest())}}class G{h;blockSize=128;outSize=32;constructor(t){const e=t instanceof Uint8Array?t:Uint8Array.from(m(t,"string"==typeof t?"hex":void 0));this.h=new Ut(Ft,e)}update(t,e){const i=t instanceof Uint8Array?t:Uint8Array.from(m(t,e));return this.h.update(i),this}digest(){return Array.from(this.h.digest())}digestHex(){return k(this.h.digest())}}const X=(t,e)=>(new j).update(t,e).digest(),Y=(t,e)=>{const i=(new j).update(t,e).digest();return(new j).update(i).digest()},J=(t,e)=>{const i=(new j).update(t,e).digest();return(new $).update(i).digest()},Z=(t,e,i)=>new W(t).update(e,i).digest(),Q=(t,e,i)=>new G(t).update(e,i).digest();function tt(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, got ${t}`)}function et(t,...e){if(!((i=t)instanceof Uint8Array||ArrayBuffer.isView(i)&&"Uint8Array"===i.constructor.name))throw new Error("Uint8Array expected");var i;if(e.length>0&&!e.includes(t.length)){const i=e.join(",");throw new Error(`Uint8Array expected of length ${i}, got length=${t.length}`)}}function it(t,e=!0){if(!0===t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&!0===t.finished)throw new Error("Hash#digest() has already been called")}function rt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function st(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function nt(t){return"string"==typeof t&&(t=function(t){if("string"!=typeof t)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(t))}(t)),et(t),t}class at{}function ot(t){const e=e=>t().update(nt(e)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}const ct=BigInt(2**32-1),ht=BigInt(32);function ut(t,e=!1){return e?{h:Number(t&ct),l:Number(t>>ht&ct)}:{h:0|Number(t>>ht&ct),l:0|Number(t&ct)}}const dt=(t,e,i)=>t>>>i,lt=(t,e,i)=>t<<32-i|e>>>i,ft=(t,e,i)=>t>>>i|e<<32-i,pt=(t,e,i)=>t<<32-i|e>>>i,gt=(t,e,i)=>t<<64-i|e>>>i-32,yt=(t,e,i)=>t>>>i-32|e<<64-i;function bt(t,e,i,r){const s=(e>>>0)+(r>>>0);return{h:t+i+(s/2**32|0)|0,l:0|s}}const mt=(t,e,i)=>(t>>>0)+(e>>>0)+(i>>>0),wt=(t,e,i,r)=>e+i+r+(t/2**32|0)|0,vt=(t,e,i,r)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),It=(t,e,i,r,s)=>e+i+r+s+(t/2**32|0)|0,kt=(t,e,i,r,s)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0)+(s>>>0),St=(t,e,i,r,s,n)=>e+i+r+s+n+(t/2**32|0)|0;class Et extends at{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,i,r){super(),this.blockLen=t,this.outputLen=e,this.padOffset=i,this.isLE=r,this.buffer=new Uint8Array(t),this.view=st(this.buffer)}update(t){it(this),et(t=nt(t));const{view:e,buffer:i,blockLen:r}=this,s=t.length;for(let n=0;n<s;){const a=Math.min(r-this.pos,s-n);if(a===r){const e=st(t);for(;r<=s-n;n+=r)this.process(e,n);continue}i.set(t.subarray(n,n+a),this.pos),this.pos+=a,n+=a,this.pos===r&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){it(this),function(t,e){et(t);const i=e.outputLen;if(t.length<i)throw new Error(`digestInto() expects output buffer of length at least ${i}`)}(t,this),this.finished=!0;const{buffer:e,view:i,blockLen:r,isLE:s}=this;let{pos:n}=this;e[n++]=128,rt(this.buffer.subarray(n)),this.padOffset>r-n&&(this.process(i,0),n=0);for(let t=n;t<r;t++)e[t]=0;!function(t,e,i,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,i,r);const s=BigInt(32),n=BigInt(4294967295),a=Number(i>>s&n),o=Number(i&n),c=r?4:0,h=r?0:4;t.setUint32(e+c,a,r),t.setUint32(e+h,o,r)}(i,r-8,BigInt(8*this.length),s),this.process(i,0);const a=st(t),o=this.outputLen;if(o%4!=0)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t<c;t++)a.setUint32(4*t,h[t],s)}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const i=t.slice(0,e);return this.destroy(),i}_cloneInto(t){t||=new this.constructor,t.set(...this.get());const{blockLen:e,buffer:i,length:r,finished:s,destroyed:n,pos:a}=this;return t.destroyed=n,t.finished=s,t.length=r,t.pos=a,r%e!==0&&t.buffer.set(i),t}clone(){return this._cloneInto()}}const xt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),_t=Uint32Array.from([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]),Pt=new Uint32Array(64);class At extends Et{A=0|xt[0];B=0|xt[1];C=0|xt[2];D=0|xt[3];E=0|xt[4];F=0|xt[5];G=0|xt[6];H=0|xt[7];constructor(t=32){super(64,t,8,!1)}get(){const{A:t,B:e,C:i,D:r,E:s,F:n,G:a,H:o}=this;return[t,e,i,r,s,n,a,o]}set(t,e,i,r,s,n,a,o){this.A=0|t,this.B=0|e,this.C=0|i,this.D=0|r,this.E=0|s,this.F=0|n,this.G=0|a,this.H=0|o}process(t,e){for(let i=0;i<16;i++,e+=4)Pt[i]=t.getUint32(e);for(let t=16;t<64;t++){const e=Pt[t-15],i=Pt[t-2],r=L(e),s=M(i);Pt[t]=_(_(r,Pt[t-7]),_(s,Pt[t-16]))}let{A:i,B:r,C:s,D:n,E:a,F:o,G:c,H:h}=this;for(let t=0;t<64;t++){const e=N(h,B(a),T(a,o,c),_t[t],Pt[t]),u=_(R(i),C(i,r,s));h=c,c=o,o=a,a=_(n,e),n=s,s=r,r=i,i=_(e,u)}this.A=_(this.A,i),this.B=_(this.B,r),this.C=_(this.C,s),this.D=_(this.D,n),this.E=_(this.E,a),this.F=_(this.F,o),this.G=_(this.G,c),this.H=_(this.H,h)}roundClean(){rt(Pt)}destroy(){rt(this.buffer),this.set(0,0,0,0,0,0,0,0)}}const Nt=ot(()=>new At),Ot=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Tt=function(t,e=!1){const i=t.length,r=new Uint32Array(i),s=new Uint32Array(i);for(let n=0;n<i;n++){const{h:i,l:a}=ut(t[n],e);r[n]=i,s[n]=a}return[r,s]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Ct=Tt[0],Rt=Tt[1],Bt=new Uint32Array(80),Lt=new Uint32Array(80);class Mt extends Et{Ah=0|Ot[0];Al=0|Ot[1];Bh=0|Ot[2];Bl=0|Ot[3];Ch=0|Ot[4];Cl=0|Ot[5];Dh=0|Ot[6];Dl=0|Ot[7];Eh=0|Ot[8];El=0|Ot[9];Fh=0|Ot[10];Fl=0|Ot[11];Gh=0|Ot[12];Gl=0|Ot[13];Hh=0|Ot[14];Hl=0|Ot[15];constructor(t=64){super(128,t,16,!1)}get(){const{Ah:t,Al:e,Bh:i,Bl:r,Ch:s,Cl:n,Dh:a,Dl:o,Eh:c,El:h,Fh:u,Fl:d,Gh:l,Gl:f,Hh:p,Hl:g}=this;return[t,e,i,r,s,n,a,o,c,h,u,d,l,f,p,g]}set(t,e,i,r,s,n,a,o,c,h,u,d,l,f,p,g){this.Ah=0|t,this.Al=0|e,this.Bh=0|i,this.Bl=0|r,this.Ch=0|s,this.Cl=0|n,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|h,this.Fh=0|u,this.Fl=0|d,this.Gh=0|l,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(t,e){for(let i=0;i<16;i++,e+=4)Bt[i]=t.getUint32(e),Lt[i]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|Bt[t-15],i=0|Lt[t-15],r=ft(e,i,1)^ft(e,i,8)^dt(e,0,7),s=pt(e,i,1)^pt(e,i,8)^lt(e,i,7),n=0|Bt[t-2],a=0|Lt[t-2],o=ft(n,a,19)^gt(n,a,61)^dt(n,0,6),c=pt(n,a,19)^yt(n,a,61)^lt(n,a,6),h=vt(s,c,Lt[t-7],Lt[t-16]),u=It(h,r,o,Bt[t-7],Bt[t-16]);Bt[t]=0|u,Lt[t]=0|h}let{Ah:i,Al:r,Bh:s,Bl:n,Ch:a,Cl:o,Dh:c,Dl:h,Eh:u,El:d,Fh:l,Fl:f,Gh:p,Gl:g,Hh:y,Hl:b}=this;for(let t=0;t<80;t++){const e=ft(u,d,14)^ft(u,d,18)^gt(u,d,41),m=pt(u,d,14)^pt(u,d,18)^yt(u,d,41),w=u&l^~u&p,v=kt(b,m,d&f^~d&g,Rt[t],Lt[t]),I=St(v,y,e,w,Ct[t],Bt[t]),k=0|v,S=ft(i,r,28)^gt(i,r,34)^gt(i,r,39),E=pt(i,r,28)^yt(i,r,34)^yt(i,r,39),x=i&s^i&a^s&a,_=r&n^r&o^n&o;y=0|p,b=0|g,p=0|l,g=0|f,l=0|u,f=0|d,({h:u,l:d}=bt(0|c,0|h,0|I,0|k)),c=0|a,h=0|o,a=0|s,o=0|n,s=0|i,n=0|r;const P=mt(E,_,k);i=wt(P,S,x,I),r=0|P}({h:i,l:r}=bt(i,r,this.Ah,this.Al)),({h:s,l:n}=bt(s,n,this.Bh,this.Bl)),({h:a,l:o}=bt(a,o,this.Ch,this.Cl)),({h:c,l:h}=bt(c,h,this.Dh,this.Dl)),({h:u,l:d}=bt(u,d,this.Eh,this.El)),({h:l,l:f}=bt(l,f,this.Fh,this.Fl)),({h:p,l:g}=bt(p,g,this.Gh,this.Gl)),({h:y,l:b}=bt(y,b,this.Hh,this.Hl)),this.set(i,r,s,n,a,o,c,h,u,d,l,f,p,g,y,b)}roundClean(){rt(Bt,Lt)}destroy(){rt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Ft=ot(()=>new Mt);class Ut extends at{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){super(),function(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash should be wrapped by utils.createHasher");tt(t.outputLen),tt(t.blockLen)}(t);const i=nt(e);if(this.iHash=t.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,s=new Uint8Array(r);s.set(i.length>r?t.create().update(i).digest():i);for(let t=0;t<s.length;t++)s[t]^=54;this.iHash.update(s),this.oHash=t.create();for(let t=0;t<s.length;t++)s[t]^=106;this.oHash.update(s),rt(s)}update(t){return it(this),this.iHash.update(t),this}digestInto(t){it(this),et(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});const{oHash:e,iHash:i,finished:r,destroyed:s,blockLen:n,outputLen:a}=this;return t.finished=r,t.destroyed=s,t.blockLen=n,t.outputLen=a,t.oHash=e._cloneInto(t.oHash??void 0),t.iHash=i._cloneInto(t.iHash??void 0),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}(()=>{const t=new ArrayBuffer(4),e=new Uint32Array(t),i=new Uint8Array(t);e[0]=16909060,i[0]})();class Dt{buffer;pos;capacity;constructor(t,e=256){if(null!=t&&t.length>0){const i=t.reduce((t,e)=>t+e.length,0);e=Math.max(e,i)}if(this.buffer=new Uint8Array(e),this.pos=0,this.capacity=e,null!=t)for(const e of t)this.write(e)}getLength(){return this.pos}toUint8Array(){return this.buffer.slice(0,this.pos)}toArray(){return Array.from(this.toUint8Array())}toUint8ArrayZeroCopy(){return this.buffer.subarray(0,this.pos)}ensureCapacity(t){if(this.pos+t>this.capacity){let e=2*this.capacity;for(;this.pos+t>e;)e*=2;const i=new Uint8Array(e);i.set(this.buffer),this.buffer=i,this.capacity=e}}write(t){const e=t instanceof Uint8Array?t:new Uint8Array(t);return this.ensureCapacity(e.length),this.buffer.set(e,this.pos),this.pos+=e.length,this}writeReverse(t){const e=t instanceof Uint8Array?t:new Uint8Array(t);this.ensureCapacity(e.length);for(let t=e.length-1;t>=0;t--)this.buffer[this.pos]=e[t],this.pos+=1;return this}writeUInt8(t){return this.ensureCapacity(1),this.buffer[this.pos]=255&t,this.pos+=1,this}writeInt8(t){return this.writeUInt8(t),this}writeUInt16LE(t){return this.ensureCapacity(2),this.buffer[this.pos]=255&t,this.buffer[this.pos+1]=t>>8&255,this.pos+=2,this}writeUInt16BE(t){return this.ensureCapacity(2),this.buffer[this.pos]=t>>8&255,this.buffer[this.pos+1]=255&t,this.pos+=2,this}writeInt16LE(t){return this.writeUInt16LE(65535&t),this}writeInt16BE(t){return this.writeUInt16BE(65535&t),this}writeUInt32LE(t){return this.ensureCapacity(4),this.buffer[this.pos]=255&t,this.buffer[this.pos+1]=t>>8&255,this.buffer[this.pos+2]=t>>16&255,this.buffer[this.pos+3]=t>>24&255,this.pos+=4,this}writeUInt32BE(t){return this.ensureCapacity(4),this.buffer[this.pos]=t>>24&255,this.buffer[this.pos+1]=t>>16&255,this.buffer[this.pos+2]=t>>8&255,this.buffer[this.pos+3]=255&t,this.pos+=4,this}writeInt32LE(t){return this.writeUInt32LE(t>>>0),this}writeInt32BE(t){return this.writeUInt32BE(t>>>0),this}writeUInt64BEBn(t){const e=t.toArray("be",8);return this.write(e),this}writeUInt64LEBn(t){const e=t.toArray("be",8);return this.writeReverse(e),this}writeUInt64LE(t){const e=new a(t).toArray("be",8);return this.writeReverse(e),this}writeVarIntNum(t){const e=se.varIntNum(t);return this.write(e),this}writeVarIntBn(t){const e=se.varIntBn(t);return this.write(e),this}reset(){this.pos=0}}class Ht{bin;pos;length;static makeReader(t,e=0){if(t instanceof Uint8Array)return new Ht(t,e);if(Array.isArray(t))return new ne(t,e);throw new Error("ReaderUint8Array.makeReader: bin must be Uint8Array or number[]")}constructor(t=new Uint8Array(0),e=0){if(t instanceof Uint8Array)this.bin=t;else{if(!Array.isArray(t))throw new Error("ReaderUint8Array constructor: bin must be Uint8Array or number[]");this.bin=new Uint8Array(t)}this.pos=e,this.length=this.bin.length}eof(){return this.pos>=this.length}read(t=this.length){const e=this.pos,i=this.pos+t;return this.pos=i,this.bin.slice(e,i)}readReverse(t=this.length){const e=new Uint8Array(t);for(let i=0;i<t;i++)e[i]=this.bin[this.pos+t-1-i];return this.pos+=t,e}readUInt8(){const t=this.bin[this.pos];return this.pos+=1,t}readInt8(){const t=this.bin[this.pos];return this.pos+=1,128&t?t-256:t}readUInt16BE(){const t=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,t}readInt16BE(){const t=this.readUInt16BE();return 32768&t?t-65536:t}readUInt16LE(){const t=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,t}readInt16LE(){const t=this.readUInt16LE();return 32768&t?t-65536:t}readUInt32BE(){const t=16777216*this.bin[this.pos]+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,t}readInt32BE(){const t=this.readUInt32BE();return 2147483648&t?t-4294967296:t}readUInt32LE(){const t=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,t}readInt32LE(){const t=this.readUInt32LE();return 2147483648&t?t-4294967296:t}readUInt64BEBn(){const t=Array.from(this.bin.slice(this.pos,this.pos+8)),e=new a(t);return this.pos=this.pos+8,e}readUInt64LEBn(){const t=Array.from(this.readReverse(8));return new a(t)}readInt64LEBn(){const t=new a(2).pow(new a(63)),e=new a(2).pow(new a(64)),i=Array.from(this.readReverse(8));let r=new a(i);return r.gte(t)&&(r=r.sub(e)),r}readVarIntNum(t=!0){const e=this.readUInt8();let i;switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(i=t?this.readInt64LEBn():this.readUInt64LEBn(),i.lte(new a(2).pow(new a(53))))return i.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return e}}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){const t=this.readUInt8();switch(t){case 253:return new a(this.readUInt16LE());case 254:return new a(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new a(t)}}}const qt="undefined"!=typeof globalThis?globalThis.Buffer:void 0,Vt=null!=qt&&"function"==typeof qt.from,Kt="0123456789abcdef",$t=new Array(256);for(let t=0;t<256;t++)$t[t]=Kt[t>>4&15]+Kt[15&t];const jt=t=>{if(Vt)return qt.from(t).toString("hex");if(0===t.length)return"";const e=new Array(t.length);for(let i=0;i<t.length;i++)e[i]=$t[255&t[i]];return e.join("")},zt=(t,e)=>t instanceof Uint8Array?t:new Uint8Array(Wt(t,e)),Wt=(t,e)=>{if(Array.isArray(t))return t.slice();if(void 0===t)return[];if("string"!=typeof t)return Array.from(t,t=>0|t);switch(e){case"hex":return Xt(t);case"base64":return function(t){if("string"!=typeof t)throw new TypeError("msg must be a string");let e=t.trim().replace(/[\r\n\t\f\v ]+/g,"");e=e.replace(/-/g,"+").replace(/_/g,"/");const i=e.indexOf("=");if(-1!==i){const t=e.slice(i);if(!/^={1,2}$/.test(t))throw new Error("Invalid base64 padding");if(e.slice(0,i).includes("="))throw new Error("Invalid base64 padding");e=e.slice(0,i)}const r=[];let s=0,n=0;for(let t=0;t<e.length;t++){const i=e.charCodeAt(t);let a=-1;if(i>=65&&i<=90)a=i-65;else if(i>=97&&i<=122)a=i-97+26;else if(i>=48&&i<=57)a=i-48+52;else if(43===i)a=62;else{if(47!==i)throw new Error(`Invalid base64 character at index ${t}`);a=63}for(s=s<<6|a,n+=6;n>=8;)n-=8,r.push(s>>n&255),s&=(1<<n)-1}return r}(t);default:return i=t,Array.from((new TextEncoder).encode(i))}var i},Gt=new Int8Array(256).fill(-1);for(let t=0;t<10;t++)Gt[48+t]=t;for(let t=0;t<6;t++)Gt[65+t]=10+t,Gt[97+t]=10+t;const Xt=t=>{p(t);const e=t.length%2==0?t:"0"+t;if(Vt)return Array.from(qt.from(e,"hex"));const i=new Array(e.length/2);let r=0;for(let t=0;t<e.length;t+=2){const s=Gt[e.charCodeAt(t)],n=Gt[e.charCodeAt(t+1)];i[r++]=s<<4|n}return i},Yt=t=>(new TextDecoder).decode(new Uint8Array(t)),Jt=(t,e)=>{switch(e){case"hex":return jt(t);case"utf8":return Yt(t);default:return t}};function Zt(t){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let i,r="";for(i=0;i<t.length;i+=3){const s=t[i],n=i+1<t.length?t[i+1]:0,a=i+2<t.length?t[i+2]:0,o=(3&s)<<4|n>>4,c=(15&n)<<2|a>>6,h=63&a;r+=e.charAt(s>>2)+e.charAt(o),r+=i+1<t.length?e.charAt(c):"=",r+=i+2<t.length?e.charAt(h):"="}return r}const Qt="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",te=t=>{if(""===t||"string"!=typeof t)throw new Error(`Expected base58 string but got “${t}”`);const e=t.match(/[IOl0]/gmu);if(null!==e)throw new Error(`Invalid base58 character “${e.join("")}”`);const i=t.match(/^1+/gmu),r=null!==i?i[0].length:0,s=(t.length-r)*(Math.log(58)/Math.log(256))+1>>>0,n=new Uint8Array([...new Uint8Array(r),...(t.match(/./gmu)??[]).map(t=>Qt.indexOf(t)).reduce((t,e)=>t.map(t=>{const i=58*t+e;return e=i>>8,i}),new Uint8Array(s)).reverse().filter((a=!1,t=>a=a||t))]);var a;return[...n]},ee=t=>{const e=Array(256).fill(-1);for(let t=0;t<58;++t)e[Qt.charCodeAt(t)]=t;const i=[];for(const r of t){let t=r;for(let r=0;r<i.length;++r){const s=(e[i[r]]<<8)+t;i[r]=Qt.charCodeAt(s%58),t=s/58|0}for(;0!==t;)i.push(Qt.charCodeAt(t%58)),t=t/58|0}for(const e of t){if(0!==e)break;i.push("1".charCodeAt(0))}return i.reverse(),String.fromCharCode(...i)},ie=(t,e=[0])=>{let i=Y([...e,...t]);return i=[...e,...t,...i.slice(0,4)],ee(i)},re=(t,e,i=1)=>{const r=te(t);let s=r.slice(0,i),n=r.slice(i,-4),a=[...s,...n];return a=Y(a),r.slice(-4).forEach((t,e)=>{if(t!==a[e])throw new Error("Invalid checksum")}),"hex"===e&&(s=jt(s),n=jt(n)),{prefix:s,data:n}};class se{bufs;length;constructor(t){this.bufs=void 0!==t?t:[],this.length=0;for(const t of this.bufs)this.length+=t.length}getLength(){return this.length}toUint8Array(){const t=new Uint8Array(this.length);let e=0;for(const i of this.bufs)t.set(i,e),e+=i.length;return t}toArray(){const t=this.length,e=new Array(t);let i=0;for(const t of this.bufs)if(t instanceof Uint8Array)for(let r=0;r<t.length;r++)e[i++]=t[r];else{const r=t;for(let t=0;t<r.length;t++)e[i++]=r[t]}return e}toHex(){return this.toArray().map(t=>t.toString(16).padStart(2,"0")).join("")}write(t){return this.bufs.push(t),this.length+=t.length,this}writeReverse(t){const e=new Array(t.length);for(let i=0;i<e.length;i++)e[i]=t[t.length-1-i];return this.write(e)}writeUInt8(t){const e=new Array(1);return e[0]=255&t,this.write(e),this}writeInt8(t){const e=new Array(1);return e[0]=255&t,this.write(e),this}writeUInt16BE(t){const e=[t>>8&255,255&t];return this.write(e)}writeInt16BE(t){return this.writeUInt16BE(65535&t)}writeUInt16LE(t){const e=[255&t,t>>8&255];return this.write(e)}writeInt16LE(t){return this.writeUInt16LE(65535&t)}writeUInt32BE(t){const e=[t>>24&255,t>>16&255,t>>8&255,255&t];return this.write(e)}writeInt32BE(t){return this.writeUInt32BE(t>>>0)}writeUInt32LE(t){const e=[255&t,t>>8&255,t>>16&255,t>>24&255];return this.write(e)}writeInt32LE(t){return this.writeUInt32LE(t>>>0)}writeUInt64BEBn(t){const e=t.toArray("be",8);return this.write(e),this}writeUInt64LEBn(t){const e=t.toArray("be",8);return this.writeReverse(e),this}writeUInt64LE(t){if(-1===t)this.write(new Array(8).fill(255));else{const e=new a(t).toArray("be",8);this.writeReverse(e)}return this}writeVarIntNum(t){const e=se.varIntNum(t);return this.write(e),this}writeVarIntBn(t){const e=se.varIntBn(t);return this.write(e),this}static varIntNum(t){let e;if(t<0)return this.varIntBn(new a(t));if(t<253)e=[t];else if(t<65536)e=[253,255&t,t>>8&255];else if(t<4294967296)e=[254,255&t,t>>8&255,t>>16&255,t>>24&255];else{const i=4294967295&t,r=4294967295&Math.floor(t/4294967296);e=[255,255&i,i>>8&255,i>>16&255,i>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255]}return e}static varIntBn(t){let e;if(t.isNeg()&&(t=t.add(ce)),t.ltn(253))e=[t.toNumber()];else if(t.ltn(65536)){const i=t.toNumber();e=[253,255&i,i>>8&255]}else if(t.lt(new a(4294967296))){const i=t.toNumber();e=[254,255&i,i>>8&255,i>>16&255,i>>24&255]}else{const i=new se;i.writeUInt8(255),i.writeUInt64LEBn(t),e=i.toArray()}return e}}class ne{bin;pos;length;constructor(t=[],e=0){this.bin=t,this.pos=e,this.length=t.length}eof(){return this.pos>=this.length}read(t=this.length){const e=this.pos,i=this.pos+t;return this.pos=i,this.bin.slice(e,i)}readReverse(t=this.length){const e=new Array(t);for(let i=0;i<t;i++)e[i]=this.bin[this.pos+t-1-i];return this.pos+=t,e}readUInt8(){const t=this.bin[this.pos];return this.pos+=1,t}readInt8(){const t=this.bin[this.pos];return this.pos+=1,128&t?t-256:t}readUInt16BE(){const t=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,t}readInt16BE(){const t=this.readUInt16BE();return 32768&t?t-65536:t}readUInt16LE(){const t=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,t}readInt16LE(){const t=this.readUInt16LE();return 32768&t?t-65536:t}readUInt32BE(){const t=16777216*this.bin[this.pos]+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,t}readInt32BE(){const t=this.readUInt32BE();return 2147483648&t?t-4294967296:t}readUInt32LE(){const t=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,t}readInt32LE(){const t=this.readUInt32LE();return 2147483648&t?t-4294967296:t}readUInt64BEBn(){const t=this.bin.slice(this.pos,this.pos+8),e=new a(t);return this.pos=this.pos+8,e}readUInt64LEBn(){const t=this.readReverse(8);return new a(t)}readInt64LEBn(){const t=this.readReverse(8);let e=new a(t);return e.gte(oe)&&(e=e.sub(ce)),e}readVarIntNum(t=!0){const e=this.readUInt8();let i;switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(i=t?this.readInt64LEBn():this.readUInt64LEBn(),i.lte(new a(2).pow(new a(53))))return i.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return e}}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){const t=this.readUInt8();switch(t){case 253:return new a(this.readUInt16LE());case 254:return new a(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new a(t)}}}const ae=t=>{if(0===t.length)return t;const e=t[t.length-1];if(127&e)return t;if(1===t.length)return[];if(128&t[t.length-2])return t;for(let i=t.length-1;i>0;i--)if(0!==t[i-1])return 128&t[i-1]?(t[i]=e,t.slice(0,i+1)):(t[i-1]|=e,t.slice(0,i));return[]},oe=new a(2).pow(new a(63)),ce=new a(2).pow(new a(64));function he(t,e="Expected a valid value, but got undefined or null."){if(null==t)throw new Error(e);return t}function ue(t,e,i){const r=-t,s=(e.X^i.X)&r,n=(e.Y^i.Y)&r,a=(e.Z^i.Z)&r;e.X^=s,i.X^=s,e.Y^=n,i.Y^=n,e.Z^=a,i.Z^=a}const de=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,le=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,fe=(1n<<256n)-1n;function pe(t){let e=t>>256n;return e=(t=(t&fe)+(e<<32n)+977n*e)>>256n,(t=(t&fe)+(e<<32n)+977n*e)>=de&&(t-=de),t}const ge=t=>pe((t%de+de)%de),ye=(t,e)=>t>=e?t-e:de-(e-t),be=(t,e)=>pe(t*e),me=(t,e)=>pe(t+e),we=t=>{let e=1n,i=0n,r=ge(t),s=de;for(;r>1n;){const t=s/r;[e,i]=[i-e*t,e],[r,s]=[s-r*t,r]}return ge(e)},ve=de+1n>>2n,Ie=BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),ke=BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),Se=new Map,Ee=t=>{const{X:e,Y:i,Z:r}=t;if(0n===i)return{X:0n,Y:1n,Z:0n};const s=be(i,i),n=be(4n,be(e,s)),a=be(3n,be(e,e)),o=ye(be(a,a),be(2n,n));return{X:o,Y:ye(be(a,ye(n,o)),be(8n,be(s,s))),Z:be(2n,be(i,r))}},xe=(t,e)=>{if(0n===t.Z)return e;if(0n===e.Z)return t;const i=be(t.Z,t.Z),r=be(e.Z,e.Z),s=be(t.X,r),n=be(e.X,i),a=be(t.Y,be(r,e.Z)),o=be(e.Y,be(i,t.Z)),c=ye(n,s),h=ye(o,a);if(0n===c)return 0n===h?Ee(t):{X:0n,Y:1n,Z:0n};const u=be(c,c),d=be(c,u),l=be(s,u),f=ye(ye(be(h,h),d),be(2n,l));return{X:f,Y:ye(be(h,ye(l,f)),be(a,d)),Z:be(c,be(t.Z,e.Z))}},_e=t=>0n===t.Z?t:{X:t.X,Y:de-t.Y,Z:t.Z},Pe=(t,e,i=5)=>{const r=`${i}:${e.x.toString(16)}:${e.y.toString(16)}`;let s,n=Se.get(r);if(void 0===n){const t=1<<i-1;n=new Array(t),s={X:e.x,Y:e.y,Z:1n},n[0]=s;const a=Ee(s);for(let e=1;e<t;e++)n[e]=xe(n[e-1],a);Se.set(r,n)}else s=n[0];const a=[],o=1n<<BigInt(i),c=o>>1n;let h=t;for(;h>0n;)if(0n==(1n&h))a.push(0),h>>=1n;else{let t=h&o-1n;t>c&&(t-=o),a.push(Number(t)),h-=t,h>>=1n}let u={X:0n,Y:1n,Z:0n};for(let t=a.length-1;t>=0;t--){u=Ee(u);const e=a[t];if(0!==e){const t=Math.abs(e)>>1,i=e>0?n[t]:_e(n[t]);u=xe(u,i)}}return u},Ae=t=>{let e=t%le;return e<0n&&(e+=le),e},Ne=(t,e)=>Ae(t*e),Oe=t=>{let e=1n,i=0n,r=Ae(t),s=le;for(;r>1n;){const t=s/r;[e,i]=[i-e*t,e],[r,s]=[s-r*t,r]}return Ae(e)};class Te extends d{x;y;inf;static _assertOnCurve(t){if(!t.validate())throw new Error("Invalid point");return t}static fromDER(t){if((4===t[0]||6===t[0]||7===t[0])&&t.length-1==64){if(6===t[0]){if(t[t.length-1]%2!=0)throw new Error("Point string value is wrong length")}else if(7===t[0]&&t[t.length-1]%2!=1)throw new Error("Point string value is wrong length");const e=new Te(t.slice(1,33),t.slice(33,65));return Te._assertOnCurve(e)}if((2===t[0]||3===t[0])&&t.length-1==32)return Te._assertOnCurve(Te.fromX(t.slice(1,33),3===t[0]));throw new Error("Unknown point format")}static fromString(t){const e=Wt(t,"hex");return Te._assertOnCurve(Te.fromDER(e))}static fromX(t,e){let i=(t=>a.isBN(t)?BigInt("0x"+t.toString(16)):"string"==typeof t?BigInt("0x"+t):Array.isArray(t)?BigInt("0x"+jt(t)):BigInt(t))(t);i=ge(i);var r;const s=(t=>{const e=((t,e)=>{let i=1n;for(t=ge(t);e>0n;)0n!=(1n&e)&&(i=be(i,t)),t=be(t,t),e>>=1n;return i})(t,ve);return be(e,e)!==ge(t)?null:e})(me(be(be(r=i,r),i),7n));if(null===s)throw new Error("Invalid point");let n=s;(1n&n)!=(e?1n:0n)&&(n=ye(de,n));const o=new a(i.toString(16),16),c=new a(n.toString(16),16);return Te._assertOnCurve(new Te(o,c))}static fromJSON(t,e){"string"==typeof t&&(t=JSON.parse(t));let i=new Te(t[0],t[1],e);if(i=Te._assertOnCurve(i),"object"!=typeof t[2]||null===t[2])return i;const r=t[2],s=t=>{const i=new Te(t[0],t[1],e);return Te._assertOnCurve(i)};return i.precomputed={beta:null,doubles:"object"==typeof r.doubles&&null!==r.doubles?{step:r.doubles.step,points:[i].concat(r.doubles.points.map(s))}:void 0,naf:"object"==typeof r.naf&&null!==r.naf?{wnd:r.naf.wnd,points:[i].concat(r.naf.points.map(s))}:void 0},i}constructor(t,e,i=!0){super("affine"),this.precomputed=null,null===t&&null===e?(this.x=null,this.y=null,this.inf=!0):(a.isBN(t)||(t=new a(t,16)),this.x=t,a.isBN(e)||(e=new a(e,16)),this.y=e,i&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),null===this.x.red&&(this.x=this.x.toRed(this.curve.red)),null===this.y.red&&(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}validate(){if(this.inf||null==this.x||null==this.y)return!1;try{const t=BigInt("0x"+this.x.fromRed().toString(16)),e=BigInt("0x"+this.y.fromRed().toString(16));return be(e,e)===me(be(be(t,t),t),7n)}catch{return!1}}encode(t=!0,e){if(this.inf)return"hex"===e?"00":[0];const i=this.curve.p.byteLength(),r=this.getX().toArray("be",i);let s;return s=t?[this.getY().isEven()?2:3].concat(r):[4].concat(r,this.getY().toArray("be",i)),"hex"!==e?s:jt(s)}toString(){return this.encode(!0,"hex")}toJSON(){return null==this.precomputed?[this.x,this.y]:[this.x,this.y,"object"==typeof this.precomputed&&null!==this.precomputed?{doubles:null!=this.precomputed.doubles?{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)}:void 0,naf:null!=this.precomputed.naf?{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}:void 0}:void 0]}inspect(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+(this.x?.fromRed()?.toString(16,2)??"undefined")+" y: "+(this.y?.fromRed()?.toString(16,2)??"undefined")+">"}isInfinity(){return this.inf}add(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return new Te(null,null);if(0===this.x?.cmp(t.x??new a(0)))return new Te(null,null);const e={X:BigInt("0x"+this.x.fromRed().toString(16)),Y:BigInt("0x"+this.y.fromRed().toString(16)),Z:1n},i={X:BigInt("0x"+t.x.fromRed().toString(16)),Y:BigInt("0x"+t.y.fromRed().toString(16)),Z:1n},r=xe(e,i);if(0n===r.Z)return new Te(null,null);const s=we(r.Z),n=be(s,s),o=be(r.X,n),c=be(r.Y,be(n,s));return new Te(o.toString(16),c.toString(16))}dbl(){if(this.inf)return this;if(null===this.x||null===this.y)throw new Error("Point coordinates cannot be null");const t=BigInt("0x"+this.x.fromRed().toString(16)),e=BigInt("0x"+this.y.fromRed().toString(16));if(0n===e)return new Te(null,null);const i=Ee({X:t,Y:e,Z:1n}),r=we(i.Z),s=be(r,r),n=be(i.X,s),a=be(i.Y,be(s,r));return new Te(n.toString(16),a.toString(16))}getX(){return(this.x??new a(0)).fromRed()}getY(){return(this.y??new a(0)).fromRed()}mul(t){if(a.isBN(t)||(t=new a(t,16)),this.inf)return this;const e=t.isNeg(),i=e?t.neg():t;let r,s,n=BigInt("0x"+i.toString(16));if(n=ge(n),0n===n)return new Te(null,null);if(0n===n)return new Te(null,null);if(null===this.x||null===this.y)throw new Error("Point coordinates cannot be null");this===this.curve.g?(r=Ie,s=ke):(r=BigInt("0x"+this.x.fromRed().toString(16)),s=BigInt("0x"+this.y.fromRed().toString(16)));const o=Pe(n,{x:r,y:s});if(0n===o.Z)return new Te(null,null);const c=we(o.Z),h=be(c,c),u=be(o.X,h),d=be(o.Y,be(h,c)),l=new a(u.toString(16),16),f=new a(d.toString(16),16),p=new Te(l,f);return e?p.neg():p}mulCT(t){if(a.isBN(t)||(t=new a(t,16)),this.inf)return new Te(null,null);const e=t.isNeg(),i=e?t.neg():t;let r=BigInt("0x"+i.toString(16));if(r=ge(r),0n===r)return new Te(null,null);let s={X:0n,Y:1n,Z:0n},n={X:this===this.curve.g?Ie:BigInt("0x"+this.getX().toString(16)),Y:this===this.curve.g?ke:BigInt("0x"+this.getY().toString(16)),Z:1n};const o=r.toString(2);for(let t=0;t<o.length;t++){const e="1"===o[t]?1n:0n;ue(e,s,n),n=xe(s,n),s=Ee(s),ue(e,s,n)}if(0n===s.Z)return new Te(null,null);const c=we(s.Z),h=be(c,c),u=be(s.X,h),d=be(s.Y,be(h,c)),l=new Te(u.toString(16),d.toString(16));return e?l.neg():l}mulAdd(t,e,i){const r=[this,e],s=[t,i];return this._endoWnafMulAdd(r,s)}jmulAdd(t,e,i){const r=[this,e],s=[t,i];return this._endoWnafMulAdd(r,s,!0)}eq(t){return this===t||this.inf===t.inf&&(this.inf||0===(this.x??new a(0)).cmp(t.x??new a(0))&&0===(this.y??new a(0)).cmp(t.y??new a(0)))}neg(t){if(this.inf)return this;const e=new Te(this.x,(this.y??new a(0)).redNeg());if(!0===t&&null!=this.precomputed){const t=this.precomputed,i=t=>t.neg();e.precomputed={naf:null!=t.naf?{wnd:t.naf.wnd,points:t.naf.points.map(i)}:void 0,doubles:null!=t.doubles?{step:t.doubles.step,points:t.doubles.points.map(t=>t.neg())}:void 0,beta:void 0}}return e}dblp(t){let e=this;for(let i=0;i<t;i++)e=e.dbl();return e}toJ(){return this.inf?new l(null,null,null):new l(this.x,this.y,this.curve.one)}_getBeta(){if("object"!=typeof this.curve.endo)return;const t=this.precomputed;if("object"==typeof t&&null!==t&&"object"==typeof t.beta&&null!==t.beta)return t.beta;const e=new Te((this.x??new a(0)).redMul(this.curve.endo.beta),this.y);if(null!=t){const i=this.curve,r=t=>{if(null===t.x)throw new Error("p.x is null");if(void 0===i.endo||null===i.endo)throw new Error("curve.endo is undefined");return new Te(t.x.redMul(i.endo.beta),t.y)};t.beta=e,e.precomputed={beta:null,naf:null!=t.naf?{wnd:t.naf.wnd,points:t.naf.points.map(r)}:void 0,doubles:null!=t.doubles?{step:t.doubles.step,points:t.doubles.points.map(r)}:void 0}}return e}_fixedNafMul(t){if("object"!=typeof this.precomputed||null===this.precomputed)throw new Error("_fixedNafMul requires precomputed values for the point");const e=this._getDoubles(),i=this.curve.getNAF(t,1,this.curve._bitLength);let r=(1<<e.step+1)-(e.step%2==0?2:1);r/=3;const s=[];for(let t=0;t<i.length;t+=e.step){let r=0;for(let s=t+e.step-1;s>=t;s--)r=(r<<1)+i[s];s.push(r)}let n=new l(null,null,null),a=new l(null,null,null);for(let t=r;t>0;t--){for(let i=0;i<s.length;i++){const r=s[i];r===t?a=a.mixedAdd(e.points[i]):r===-t&&(a=a.mixedAdd(e.points[i].neg()))}n=n.add(a)}return n.toP()}_wnafMulAdd(t,e,i,r,s){const n=this.curve._wnafT1.map(t=>t.toNumber()),o=this.curve._wnafT2.map(()=>[]),c=this.curve._wnafT3.map(()=>[]);let h=0;for(let i=0;i<r;i++){const r=e[i]._getNAFPoints(t);n[i]=r.wnd,o[i]=r.points}for(let t=r-1;t>=1;t-=2){const r=t-1,s=t;if(1!==n[r]||1!==n[s]){c[r]=this.curve.getNAF(i[r],n[r],this.curve._bitLength),c[s]=this.curve.getNAF(i[s],n[s],this.curve._bitLength),h=Math.max(c[r].length,h),h=Math.max(c[s].length,h);continue}const u=[e[r],null,null,e[s]];0===(e[r].y??new a(0)).cmp(e[s].y??new a(0))?(u[1]=e[r].add(e[s]),u[2]=e[r].toJ().mixedAdd(e[s].neg())):0===(e[r].y??new a(0)).cmp((e[s].y??new a(0)).redNeg())?(u[1]=e[r].toJ().mixedAdd(e[s]),u[2]=e[r].add(e[s].neg())):(u[1]=e[r].toJ().mixedAdd(e[s]),u[2]=e[r].toJ().mixedAdd(e[s].neg()));const d=[-3,-1,-5,-7,0,7,5,1,3],l=this.curve.getJSF(i[r],i[s]);h=Math.max(l[0].length,h),c[r]=new Array(h),c[s]=new Array(h);for(let t=0;t<h;t++){const e=0|l[0][t],i=0|l[1][t];c[r][t]=d[3*(e+1)+(i+1)],c[s][t]=0,o[r]=u}}let u=new l(null,null,null);const d=this.curve._wnafT4;for(let t=h;t>=0;t--){let e=0;for(;t>=0;){let i=!0;for(let e=0;e<r;e++)d[e]=new a("number"==typeof c[e][t]?c[e][t]:0),d[e].isZero()||(i=!1);if(!i)break;e++,t--}if(t>=0&&e++,u=u.dblp(e),t<0)break;const i=new a(1),s=new a(2);for(let t=0;t<r;t++){const e=d[t];let r;0!==e.cmpn(0)&&(r=e.isNeg()?o[t][e.neg().sub(i).div(s).toNumber()].neg():o[t][e.sub(i).div(s).toNumber()],u="affine"===r.type?u.mixedAdd(r):u.add(r))}}for(let t=0;t<r;t++)o[t]=[];return!0===s?u:u.toP()}_endoWnafMulAdd(t,e,i){const r=new Array(2*t.length),s=new Array(2*t.length);let n;for(n=0;n<t.length;n++){const i=this.curve._endoSplit(e[n]);let a=t[n],o=a._getBeta()??new Te(null,null);0!==i.k1.negative&&(i.k1.ineg(),a=a.neg(!0)),0!==i.k2.negative&&(i.k2.ineg(),o=o.neg(!0)),r[2*n]=a,r[2*n+1]=o,s[2*n]=i.k1,s[2*n+1]=i.k2}const a=this._wnafMulAdd(1,r,s,2*n,i);for(let t=0;t<2*n;t++)r[t]=null,s[t]=null;return a}_hasDoubles(t){if(null==this.precomputed)return!1;const e=this.precomputed.doubles;return"object"==typeof e&&e.points.length>=Math.ceil((t.bitLength()+1)/e.step)}_getDoubles(t,e){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.doubles&&null!==this.precomputed.doubles)return this.precomputed.doubles;const i=[this];let r=this;for(let s=0;s<(e??0);s+=t??1){for(let e=0;e<(t??1);e++)r=r.dbl();i.push(r)}return{step:t??1,points:i}}_getNAFPoints(t){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.naf&&null!==this.precomputed.naf)return this.precomputed.naf;const e=[this],i=(1<<t)-1,r=1===i?null:this.dbl();for(let t=1;t<i;t++)null!==r&&(e[t]=e[t-1].add(r));return{wnd:t,points:e}}}let Ce;class Re{p;red;redN;zero;one;two;g;n;a;b;tinv;zeroA;threeA;endo;_endoWnafT1;_endoWnafT2;_wnafT1;_wnafT2;_wnafT3;_wnafT4;_bitLength;static assert(t,e="Elliptic curve assertion failed"){if(!t)throw new Error(e)}getNAF(t,e,i){const r=new Array(Math.max(t.bitLength(),i)+1);r.fill(0);const s=1<<e+1,n=t.clone();for(let t=0;t<r.length;t++){let e;const i=n.andln(s-1);n.isOdd()?(e=i>(s>>1)-1?(s>>1)-i:i,n.isubn(e)):e=0,r[t]=e,n.iushrn(1)}return r}getJSF(t,e){const i=[[],[]];t=t.clone(),e=e.clone();let r=0,s=0;for(;t.cmpn(-r)>0||e.cmpn(-s)>0;){let n,a,o=t.andln(3)+r&3,c=e.andln(3)+s&3;if(3===o&&(o=-1),3===c&&(c=-1),1&o){const e=t.andln(7)+r&7;n=3!==e&&5!==e||2!==c?o:-o}else n=0;if(i[0].push(n),1&c){const t=e.andln(7)+s&7;a=3!==t&&5!==t||2!==o?c:-c}else a=0;i[1].push(a),2*r===n+1&&(r=1-r),2*s===a+1&&(s=1-s),t.iushrn(1),e.iushrn(1)}return i}static cachedProperty(t,e,i){const r="_"+e;t.prototype[e]=function(){return void 0!==this[r]?this[r]:this[r]=i.call(this)}}static parseBytes(t){return"string"==typeof t?Wt(t,"hex"):t}static intFromLE(t){return new a(t,"hex","le")}constructor(){if(void 0!==Ce)return Ce;Ce=this;const t={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",beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",{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"]]}}]};this.p=new a(t.p,16),this.red=new h(t.prime),this.zero=new a(0).toRed(this.red),this.one=new a(1).toRed(this.red),this.two=new a(2).toRed(this.red),this.n=new a(t.n,16),this.g=Te.fromJSON(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.bitLength(),this.redN=this.n.toRed(this.red),this.a=new a(t.a,16).toRed(this.red),this.b=new a(t.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(t),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}_getEndomorphism(t){if(!this.zeroA||1!==this.p.modrn(3))return;let e,i,r;if(void 0!==t.beta)e=new a(t.beta,16).toRed(this.red);else{const t=this._getEndoRoots(this.p);if(null===t)throw new Error("Failed to get endomorphism roots for beta.");e=t[0].cmp(t[1])<0?t[0]:t[1],e=e.toRed(this.red)}if(void 0!==t.lambda)i=new a(t.lambda,16);else{const t=this._getEndoRoots(this.n);if(null===t)throw new Error("Failed to get endomorphism roots for lambda.");if(null==this.g)throw new Error("Curve generator point (g) is not defined.");const r=this.g.mul(t[0])?.x,s=null!=this.g.x?this.g.x.redMul(e):void 0;if(null!=r&&null!=s&&0===r.cmp(s))i=t[0];else{if(i=t[1],null==this.g)throw new Error("Curve generator point (g) is not defined.");const r=this.g.mul(i)?.x,s=null!=this.g.x?this.g.x.redMul(e):void 0;if(null==r||null==s)throw new Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");Re.assert(0===r.cmp(s),"Lambda selection does not match computed beta.")}}return r="object"==typeof t.basis&&null!==t.basis?t.basis.map(function(t){return{a:new a(t.a,16),b:new a(t.b,16)}}):this._getEndoBasis(i),{beta:e,lambda:i,basis:r}}_getEndoRoots(t){const e=t===this.p?this.red:new u(t),i=new a(2).toRed(e).redInvm(),r=i.redNeg(),s=new a(3).toRed(e).redNeg().redSqrt().redMul(i);return[r.redAdd(s).fromRed(),r.redSub(s).fromRed()]}_getEndoBasis(t){const e=this.n.ushrn(Math.floor(this.n.bitLength()/2));let i,r,s,n,o,c,h=t,u=this.n.clone(),d=new a(1),l=new a(0),f=new a(0),p=new a(1),g=new a(0),y=0,b=new a(0),m=new a(0);for(;0!==h.cmpn(0);){const t=u.div(h);b=u.sub(t.mul(h)),m=f.sub(t.mul(d));const a=p.sub(t.mul(l));if(void 0===s&&b.cmp(e)<0)i=g.neg(),r=d,s=b.neg(),n=m;else if(void 0!==s&&2===++y)break;g=b,u=h,h=b,f=d,d=m,p=l,l=a}if(void 0===i||void 0===r||void 0===s||void 0===n)throw new Error("Failed to compute Endo Basis values");o=b.neg(),c=m;const w=s.sqr().add(n.sqr());return o.sqr().add(c.sqr()).cmp(w)>=0&&(o=i,c=r),0!==s.negative&&(s=s.neg(),n=n.neg()),0!==o.negative&&(o=o.neg(),c=c.neg()),[{a:s,b:n},{a:o,b:c}]}_endoSplit(t){if(null==this.endo)throw new Error("Endomorphism is not defined.");const e=this.endo.basis,i=e[0],r=e[1],s=r.b.mul(t).divRound(this.n),n=i.b.neg().mul(t).divRound(this.n),a=s.mul(i.a),o=n.mul(r.a),c=s.mul(i.b),h=n.mul(r.b);return{k1:t.sub(a).sub(o),k2:c.add(h).neg()}}validate(t){if(t.inf)return!0;const e=t.x,i=t.y;if(null===e||null===i)throw new Error("Point coordinates cannot be null");const r=this.a.redMul(e),s=e.redSqr().redMul(e).redIAdd(r).redIAdd(this.b);return 0===i.redSqr().redISub(s).cmpn(0)}}class Be{r;s;static fromDER(t,e){const i=(t,e)=>{const i=t[e.place++];if(128&i)throw new Error("Invalid DER entity length");return i};t=Wt(t,e);const r=new class{place;constructor(){this.place=0}};if(48!==t[r.place++])throw new Error("Signature DER must start with 0x30");if(i(t,r)+r.place!==t.length)throw new Error("Signature DER invalid");if(2!==t[r.place++])throw new Error("Signature DER invalid");const s=i(t,r);let n=t.slice(r.place,s+r.place);if(r.place+=s,2!==t[r.place++])throw new Error("Signature DER invalid");const o=i(t,r);if(t.length!==o+r.place)throw new Error("Invalid R-length in signature DER");let c=t.slice(r.place,o+r.place);if(0===n[0]){if(!(128&n[1]))throw new Error("Invalid R-value in signature DER");n=n.slice(1)}if(0===c[0]){if(!(128&c[1]))throw new Error("Invalid S-value in signature DER");c=c.slice(1)}return new Be(new a(n),new a(c))}static fromCompact(t,e){if(65!==(t=Wt(t,e)).length)throw new Error("Invalid Compact Signature");const i=t[0];if(i<27||i>=35)throw new Error("Invalid Compact Byte");return new Be(new a(t.slice(1,33)),new a(t.slice(33,65)))}constructor(t,e){this.r=t,this.s=e}verify(t,e,i){const r=new a(X(t,i),16);return Ke(r,this,e)}toString(t){return this.toDER(t)}toDER(t){const e=(t,e)=>{if(!(e<128))throw new Error("len must be < 0x80");t.push(e)},i=t=>{let e=0;const i=t.length-1;for(;0===t[e]&&!(128&t[e+1])&&e<i;)e++;return 0===e?t:t.slice(e)};let r=this.r.toArray(),s=this.s.toArray();for(128&r[0]&&(r=[0].concat(r)),128&s[0]&&(s=[0].concat(s)),r=i(r),s=i(s);0===s[0]&&!(128&s[1]);)s=s.slice(1);let n=[2];e(n,r.length),n=n.concat(r),n.push(2),e(n,s.length);const a=n.concat(s);let o=[48];return e(o,a.length),o=o.concat(a),"hex"===t?jt(o):"base64"===t?Zt(o):o}toCompact(t,e,i){if(t<0||t>3)throw new Error("Invalid recovery param");if("boolean"!=typeof e)throw new Error("Invalid compressed param");let r=27+t;e&&(r+=4);let s=[r];return s=s.concat(this.r.toArray("be",32)),s=s.concat(this.s.toArray("be",32)),"hex"===i?jt(s):"base64"===i?Zt(s):s}RecoverPublicKey(t,e){const i=this.r,r=this.s,s=!!(1&t),n=t>>1,a=new Re,o=a.n,c=a.g,h=0!==n?i.add(o):i,u=Te.fromX(h,s);if(!u.mul(o).isInfinity())throw new Error("nR is not at infinity");const d=e.neg().umod(o),l=i.invm(o),f=l.mul(r).umod(o),p=l.mul(d).umod(o),g=c.mul(p).add(u.mul(f)),y=new $e(g);return y.validate(),y}CalculateRecoveryFactor(t,e){for(let i=0;i<4;i++){let r;try{r=this.RecoverPublicKey(i,e)}catch{continue}if(t.eq(r))return i}throw new Error("Unable to find valid recovery factor")}}class Le{K;V;constructor(t,e){const i=Wt(t,"hex"),r=Wt(e,"hex");if(32!==i.length)throw new Error("Entropy must be exactly 32 bytes (256 bits)");if(32!==r.length)throw new Error("Nonce must be exactly 32 bytes (256 bits)");const s=i.concat(r);this.K=new Array(32),this.V=new Array(32);for(let t=0;t<32;t++)this.K[t]=0,this.V[t]=1;this.update(s)}hmac(){return new W(this.K)}update(t){let e=this.hmac().update(this.V).update([0]);void 0!==t&&(e=e.update(t)),this.K=e.digest(),this.V=this.hmac().update(this.V).digest(),void 0!==t&&(this.K=this.hmac().update(this.V).update([1]).update(t).digest(),this.V=this.hmac().update(this.V).digest())}generate(t){let e=[];for(;e.length<t;)this.V=this.hmac().update(this.V).digest(),e=e.concat(this.V);const i=e.slice(0,t);return this.update(),jt(i)}}function Me(t,e,i=new Re){const r=8*t.byteLength()-i.n.bitLength();return r>0&&t.iushrn(r),!0!==e&&t.cmp(i.n)>=0?t.sub(i.n):t}function Fe(t){const e=t.toArray("be");let i=0n;for(let t=0;t<e.length;t++)i=i<<8n|BigInt(e[t]);return i}const Ue=new Re,De=Ue.n.byteLength(),He=Ue.n.subn(1),qe=le>>1n,Ve=(t,e,i=!1,r)=>{const s=Ue.n.bitLength();if(t.bitLength()>s)throw new Error(`ECDSA message is too large: expected <= ${s} bits. Callers must hash messages before signing.`);const n=Fe(t=Me(t)),o=Fe(e),c=e.toArray("be",De),h=t.toArray("be",De),u=new Le(c,h);for(let t=0;;t++){let e="function"==typeof r?r(t):a.isBN(r)?r:new a(u.generate(De),16);if(null==e)throw new Error("k is undefined");if(e=Me(e,!0),e.cmpn(1)<0||e.cmp(He)>0){if(a.isBN(r))throw new Error("Invalid fixed custom K value (must be >1 and <N-1)");continue}const s=Ue.g.mulCT(e);if(s.isInfinity()){if(a.isBN(r))throw new Error("Invalid fixed custom K value (k·G at infinity)");continue}const c=BigInt("0x"+s.getX().toString(16)),h=Ae(c);if(0n===h){if(a.isBN(r))throw new Error("Invalid fixed custom K value (r == 0)");continue}const d=BigInt("0x"+e.toString(16)),l=Oe(d),f=Ne(h,o),p=Ae(n+f);let g=Ne(l,p);if(0n===g){if(a.isBN(r))throw new Error("Invalid fixed custom K value (s == 0)");continue}i&&g>qe&&(g=le-g);const y=new a(h.toString(16),16),b=new a(g.toString(16),16);return new Be(y,b)}},Ke=(t,e,i)=>{const r=Ue.n.bitLength();if(t.bitLength()>r)return!1;const s=Fe(t);if(null==i.x||null==i.y)throw new Error("Invalid public key: missing coordinates.");const n={x:Fe(i.x),y:Fe(i.y)},a={r:Fe(e.r),s:Fe(e.s)},{r:o,s:c}=a,h=s;if(o<=0n||o>=le||c<=0n||c>=le)return!1;const u=Oe(c);if(0n===u)return!1;const d=Ne(h,u),l=Ne(o,u),f=Pe(d,{x:Ie,y:ke}),p=Pe(l,n),g=xe(f,p);if(0n===g.Z)return!1;const y=we(g.Z),b=be(y,y),m=be(g.X,b);return Ae(m)===o};class $e extends Te{static fromPrivateKey(t){const e=(new Re).g.mul(t);return new $e(e.x,e.y)}static fromString(t){const e=Te.fromString(t);return new $e(e.x,e.y)}static fromDER(t){const e=Te.fromDER(t);return new $e(e.x,e.y)}constructor(t,e=null,i=!0){if(t instanceof Te)super(t.getX(),t.getY());else{if(null===e&&i&&"string"==typeof t&&(66===t.length||130===t.length))throw new Error('You are using the "new PublicKey()" constructor with a DER hex string. You need to use "PublicKey.fromString()" instead.');super(t,e,i)}}deriveSharedSecret(t){if(!this.validate())throw new Error("Public key not valid for ECDH secret derivation");return this.mulCT(t)}verify(t,e,i){const r=new a(X(t,i),16);return Ke(r,e,this)}toDER(t){return"hex"===t?this.encode(!0,t):this.encode(!0)}toHash(t){const e=J(this.encode(!0));return"hex"===t?jt(e):e}toAddress(t=[0]){if("string"==typeof t)if("testnet"===t||"test"===t)t=[111];else{if("mainnet"!==t&&"main"!==t)throw new Error(`Invalid prefix ${t}`);t=[0]}return ie(this.toHash(),t)}deriveChild(t,e,i,r){let s;if("function"==typeof r){const e=r(t,this);void 0!==e?s=e:(s=this.deriveSharedSecret(t),"function"==typeof i&&i(t,this,s))}else s=this.deriveSharedSecret(t);const n=Wt(e,"utf8"),o=Z(s.encode(!0),n),c=(new Re).g.mul(new a(o)),h=this.add(c);return new $e(h.x,h.y)}static fromMsgHashAndCompactSignature(t,e,i){const r=Wt(e,i);if(65!==r.length)throw new Error("Invalid Compact Signature");const s=r[0];if(s<27||s>=35)throw new Error("Invalid Compact Byte");let n=r[0]-27;return n>3&&(n-=4),new Be(new a(r.slice(1,33)),new a(r.slice(33,65))).RecoverPublicKey(n,t)}}class je{_rand;getRandomValues(t,e){const i=new Uint8Array(e);return t.crypto.getRandomValues(i),Array.from(i)}constructor(){const t=()=>{throw new Error("No secure random number generator is available in this environment.")};if(this._rand=t,"undefined"==typeof globalThis||"function"!=typeof globalThis.crypto?.getRandomValues){if("undefined"!=typeof process&&"node"===process.release?.name)try{const t=require("crypto");if("function"==typeof t.randomBytes)return void(this._rand=e=>Array.from(t.randomBytes(e)))}catch(t){}"undefined"==typeof self||"function"!=typeof self.crypto?.getRandomValues?"undefined"==typeof window||"function"!=typeof window.crypto?.getRandomValues?this._rand=t:this._rand=t=>this.getRandomValues(window,t):this._rand=t=>this.getRandomValues(self,t)}else this._rand=t=>this.getRandomValues(globalThis,t)}generate(t){return this._rand(t)}}let ze=null;const We=t=>(null==ze&&(ze=new je),ze.generate(t));class Ge{x;y;constructor(t,e){const i=(new Re).p;this.x=t.umod(i),this.y=e.umod(i)}toString(){return ee(this.x.toArray())+"."+ee(this.y.toArray())}static fromString(t){const[e,i]=t.split(".");return new Ge(new a(te(e)),new a(te(i)))}}class Xe{points;threshold;constructor(t,e){this.points=t,this.threshold=e??t.length}static fromPrivateKey(t,e){const i=(new Re).p,r=[new Ge(new a(0),new a(t.toArray()))];for(let t=1;t<e;t++){const t=new a(We(32)).umod(i),e=new a(We(32)).umod(i);r.push(new Ge(t,e))}return new Xe(r)}valueAt(t){const e=(new Re).p;let i=new a(0);for(let r=0;r<this.threshold;r++){let s=this.points[r].y;for(let i=0;i<this.threshold;i++)if(r!==i){const n=this.points[i].x,a=this.points[r].x,o=t.sub(n).umod(e),c=a.sub(n).umod(e).invm(e),h=o.mul(c).umod(e);s=s.mul(h).umod(e)}i=i.add(s).umod(e)}return i}}class Ye{points;threshold;integrity;constructor(t,e,i){this.points=t,this.threshold=e,this.integrity=i}static fromBackupFormat(t){let e=0,i="";const r=t.map((t,r)=>{const s=t.split(".");if(4!==s.length)throw new Error("Invalid share format in share "+r.toString()+'. Expected format: "x.y.t.i" - received '+t);const[n,a,o,c]=s;if(void 0===o)throw new Error("Threshold not found in share "+r.toString());if(void 0===c)throw new Error("Integrity not found in share "+r.toString());const h=parseInt(o);if(0!==r&&e!==h)throw new Error("Threshold mismatch in share "+r.toString());if(0!==r&&i!==c)throw new Error("Integrity mismatch in share "+r.toString());return e=h,i=c,Ge.fromString([n,a].join("."))});return new Ye(r,e,i)}toBackupFormat(){return this.points.map(t=>t.toString()+"."+this.threshold.toString()+"."+this.integrity)}}class Je extends a{static fromRandom(){return new Je(We(32))}static fromString(t,e="hex"){return new Je(super.fromString(t,e).toArray())}static fromHex(t){return new Je(super.fromHex(t,"big"))}static fromWif(t,e=1){const i=re(t,void 0,e);if(33!==i.data.length)throw new Error("Invalid WIF length");if(1!==i.data[32])throw new Error("Invalid WIF padding");return new Je(i.data.slice(0,32))}constructor(t=0,e=10,i="be",r="apply"){if(t instanceof a?(super(),t.copy(this)):super(t,e,i),"nocheck"!==r){const t=this.checkInField();if(!t.inField){if("error"===r)throw new Error("Input is out of field");a.move(this,t.modN)}}}checkInField(){const t=new Re,e=this.mod(t.n);return{inField:0===this.cmp(e),modN:e}}isValid(){return this.checkInField().inField}sign(t,e,i=!0,r){const s=new a(X(t,e),16);return Ve(s,this,i,r)}verify(t,e,i){const r=new a(X(t,i),16);return Ke(r,e,this.toPublicKey())}toPublicKey(){const t=(new Re).g.mulCT(this);return new $e(t.x,t.y)}toWif(t=[128]){if(!this.isValid())throw new Error("Value is out of field");return ie([...this.toArray("be",32),1],t)}toAddress(t=[0]){return this.toPublicKey().toAddress(t)}toHex(){return super.toHex(32)}toString(t="hex",e=64){return super.toString(t,e)}deriveSharedSecret(t){if(!t.validate())throw new Error("Public key not valid for ECDH secret derivation");return t.mulCT(this)}deriveChild(t,e,i,r){let s;if("function"==typeof r){const e=r(this,t);void 0!==e?s=e:(s=this.deriveSharedSecret(t),"function"==typeof i&&i(this,t,s))}else s=this.deriveSharedSecret(t);const n=Wt(e,"utf8"),o=Z(s.encode(!0),n),c=new Re;return new Je(this.add(new a(o)).mod(c.n).toArray())}toKeyShares(t,e){if("number"!=typeof t||"number"!=typeof e)throw new Error("threshold and totalShares must be numbers");if(t<2)throw new Error("threshold must be at least 2");if(e<2)throw new Error("totalShares must be at least 2");if(t>e)throw new Error("threshold should be less than or equal to totalShares");const i=Xe.fromPrivateKey(this,t),r=[],s=new Set,n=new Re,o=We(64);for(let t=0;t<e;t++){let e,c=0;do{const i=[t,c,...We(32)],r=Q(o,i);if(e=new a(r).umod(n.p),c++,c>5)throw new Error("Failed to generate unique x coordinate after 5 attempts")}while(e.isZero()||s.has(e.toString()));s.add(e.toString());const h=i.valueAt(e);r.push(new Ge(e,h))}const c=this.toPublicKey().toHash("hex").slice(0,8);return new Ye(r,t,c)}toBackupShares(t,e){return this.toKeyShares(t,e).toBackupFormat()}static fromBackupShares(t){return Je.fromKeyShares(Ye.fromBackupFormat(t))}static fromKeyShares(t){const{points:e,threshold:i,integrity:r}=t;if(i<2)throw new Error("threshold must be at least 2");if(e.length<i)throw new Error(`At least ${i} shares are required to reconstruct the private key`);for(let t=0;t<i;t++)for(let r=t+1;r<i;r++)if(e[t].x.eq(e[r].x))throw new Error("Duplicate share detected, each must be unique.");const s=new Xe(e,i),n=new Je(s.valueAt(new a(0)).toArray());if(n.toPublicKey().toHash("hex").slice(0,8)!==r)throw new Error("Integrity hash mismatch");return n}}const Ze=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),Qe=[[0,0,0,0],[1,0,0,0],[2,0,0,0],[4,0,0,0],[8,0,0,0],[16,0,0,0],[32,0,0,0],[64,0,0,0],[128,0,0,0],[27,0,0,0],[54,0,0,0]].map(t=>new Uint8Array(t)),ti=new Uint8Array(256),ei=new Uint8Array(256);for(let t=0;t<256;t++){const e=255&(t<<1^(128&t?27:0));ti[t]=e,ei[t]=e^t}function ii(t){for(let e=0;e<4;e++){const i=t[0][e],r=t[1][e],s=t[2][e],n=t[3][e];t[0][e]=ti[i]^ei[r]^s^n,t[1][e]=i^ti[r]^ei[s]^n,t[2][e]=i^r^ti[s]^ei[n],t[3][e]=ei[i]^r^s^ti[n]}}function ri(t,e,i){for(let r=0;r<4;r++){const s=e[i+r];for(let e=0;e<4;e++)t[e][r]^=s[e]}}function si(t){for(let e=0;e<4;e++)for(let i=0;i<4;i++)t[e][i]=Ze[t[e][i]]}function ni(t){for(let e=0;e<4;e++)t[e]=Ze[t[e]]}function ai(t){const e=t[0];t[0]=t[1],t[1]=t[2],t[2]=t[3],t[3]=e}function oi(t){let e=t[1][0];t[1][0]=t[1][1],t[1][1]=t[1][2],t[1][2]=t[1][3],t[1][3]=e,e=t[2][0];const i=t[2][1];t[2][0]=t[2][2],t[2][1]=t[2][3],t[2][2]=e,t[2][3]=i,e=t[3][3],t[3][3]=t[3][2],t[3][2]=t[3][1],t[3][1]=t[3][0],t[3][0]=e}function ci(t,e){let i,r,s,n;const a=[[],[],[],[]],o=[],c=Array.from(e);if(16===c.length)n=11;else if(24===c.length)n=13;else{if(32!==c.length)throw new Error("Illegal key length: "+String(c.length));n=15}const h=function(t,e){const i=e.length/4,r=[];for(let t=0;t<e.length;t++)t%4==0&&r.push([]),r[t>>2].push(e[t]);for(let e=i;e<4*t;e++){r[e]=[];const t=r[e-1].slice();if(e%i===0){ai(t),ni(t);const r=Qe[e/i];for(let e=0;e<4;e++)t[e]^=r[e]}else i>6&&e%i===4&&ni(t);for(let s=0;s<4;s++)r[e][s]=r[e-i][s]^t[s]}return r}(n,c);for(let e=0;e<4;e++)a[0][e]=t[4*e],a[1][e]=t[4*e+1],a[2][e]=t[4*e+2],a[3][e]=t[4*e+3];for(ri(a,h,0),s=1;s<n;s++)si(a),oi(a),s+1<n&&ii(a),ri(a,h,4*s);for(i=0;i<4;i++)for(r=0;r<4;r++)o.push(a[r][i]);return o}const hi=function(t){if(t<0||t>Number.MAX_SAFE_INTEGER)throw new Error("getBytes64: value out of range");const e=Math.floor(t/4294967296),i=t>>>0;return[e>>>24&255,e>>>16&255,e>>>8&255,255&e,i>>>24&255,i>>>16&255,i>>>8&255,255&i]},ui=function(t){return new Uint8Array(t)},di=(()=>{const t=new Uint8Array(16);return t[0]=225,t})(),li=(...t)=>{let e=0;for(const i of t)e+=i.length;const i=new Uint8Array(e);let r=0;for(const e of t)i.set(e,r),r+=e.length;return i},fi=function(t){let e=0,i=0;for(let r=0;r<t.length;r++)i=e,e=1&t[r],t[r]=t[r]>>1,0!==i&&(t[r]=128|t[r]);return t},pi=function(t,e){const i=e.slice(),r=ui(16);for(let e=0;e<16;e++){const s=t[e];for(let t=7;t>=0;t--){const e=255&-(s>>t&1);for(let t=0;t<16;t++)r[t]^=i[t]&e;const n=255&-(1&i[15]);fi(i);for(let t=0;t<16;t++)i[t]^=di[t]&n}}return r},gi=function(t){const e=t.slice();for(let t=15;t>11&&(e[t]=e[t]+1&255,0===e[t]);t--);return e};function yi(t,e){let i=ui(16);const r=new Uint8Array(16);for(let s=0;s<t.length;s+=16){r.set(i);for(let e=0;e<16;e++)r[e]^=t[s+e]??0;i=pi(r,e)}return i}function bi(t,e,i){if(0===t.length)return new Uint8Array(0);const r=new Uint8Array(t.length);let s=e.slice(),n=0;const a=Math.ceil(t.length/16);for(let e=0;e<a;e++){const o=ci(s,i),c=Math.min(16,t.length-n);for(let e=0;e<c;e++)r[n]=t[n]^o[e],n++;e+1<a&&(s=gi(s))}return r}function mi(t){const e=8*t.length;let i;i=0===t.length?16:t.length%16==0?0:16-t.length%16;const r=16+t.length+i+16,s=new Uint8Array(r);let n=0;n+=16,s.set(t,n),n+=t.length,n+=i;const a=hi(0);s.set(a,n),n+=8;const o=hi(e);return s.set(o,n),s}class wi extends a{static fromRandom(){return new wi(We(32))}encrypt(t,e){const i=new Uint8Array(We(32)),r=new Uint8Array(Wt(t,e)),s=new Uint8Array(this.toArray("be",32)),{result:n,authenticationTag:a}=function(t,e,i){if(0===e.length)throw new Error("Initialization vector must not be empty");if(0===i.length)throw new Error("Key must not be empty");const r=new Uint8Array(ci(ui(16),i));let s;if(12===e.length)s=li(e,ui(3),new Uint8Array([1]));else{let t=e;t.length%16!=0&&(t=li(t,ui(16-t.length%16)));const i=hi(8*e.length);s=yi(li(t,ui(8),new Uint8Array(i)),r)}const n=bi(t,gi(s),i);return{result:n,authenticationTag:bi(yi(mi(n),r),s,i)}}(r,i,s),o=i.length+n.length+a.length,c=new Uint8Array(o);let h=0;return c.set(i,h),h+=i.length,c.set(n,h),h+=n.length,c.set(a,h),Jt(Array.from(c),e)}decrypt(t,e){const i=new Uint8Array(Wt(t,e));if(i.length<48)throw new Error("Ciphertext too short");const r=i.slice(0,32),s=i.length-16,n=function(t,e,i,r){if(0===t.length)throw new Error("Cipher text must not be empty");if(0===e.length)throw new Error("Initialization vector must not be empty");if(0===r.length)throw new Error("Key must not be empty");const s=new Uint8Array(ci(ui(16),r));let n;if(12===e.length)n=li(e,ui(3),new Uint8Array([1]));else{let t=e;t.length%16!=0&&(t=li(t,ui(16-t.length%16)));const i=hi(8*e.length);n=yi(li(t,ui(8),new Uint8Array(i)),s)}const a=bi(t,gi(n),r),o=bi(yi(mi(t),s),n,r);if(o.length!==i.length)return null;let c=0;for(let t=0;t<o.length;t++)c|=o[t]^i[t];return 0!==c?null:a}(i.slice(32,s),r,i.slice(s),new Uint8Array(this.toArray("be",32)));if(null===n)throw new Error("Decryption failed!");return Jt(Array.from(n),e)}}const vi={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SPLIT:127,OP_NUM2BIN:128,OP_BIN2NUM:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_NOP3:178,OP_NOP4:179,OP_SUBSTR:179,OP_NOP5:180,OP_LEFT:180,OP_NOP6:181,OP_RIGHT:181,OP_NOP7:182,OP_LSHIFTNUM:182,OP_NOP8:183,OP_RSHIFTNUM:183,OP_NOP9:184,OP_NOP10:185,OP_NOP11:186,OP_NOP12:187,OP_NOP13:188,OP_NOP14:189,OP_NOP15:190,OP_NOP16:191,OP_NOP17:192,OP_NOP18:193,OP_NOP19:194,OP_NOP20:195,OP_NOP21:196,OP_NOP22:197,OP_NOP23:198,OP_NOP24:199,OP_NOP25:200,OP_NOP26:201,OP_NOP27:202,OP_NOP28:203,OP_NOP29:204,OP_NOP30:205,OP_NOP31:206,OP_NOP32:207,OP_NOP33:208,OP_NOP34:209,OP_NOP35:210,OP_NOP36:211,OP_NOP37:212,OP_NOP38:213,OP_NOP39:214,OP_NOP40:215,OP_NOP41:216,OP_NOP42:217,OP_NOP43:218,OP_NOP44:219,OP_NOP45:220,OP_NOP46:221,OP_NOP47:222,OP_NOP48:223,OP_NOP49:224,OP_NOP50:225,OP_NOP51:226,OP_NOP52:227,OP_NOP53:228,OP_NOP54:229,OP_NOP55:230,OP_NOP56:231,OP_NOP57:232,OP_NOP58:233,OP_NOP59:234,OP_NOP60:235,OP_NOP61:236,OP_NOP62:237,OP_NOP63:238,OP_NOP64:239,OP_NOP65:240,OP_NOP66:241,OP_NOP67:242,OP_NOP68:243,OP_NOP69:244,OP_NOP70:245,OP_NOP71:246,OP_NOP72:247,OP_NOP73:248,OP_NOP77:252,OP_SMALLDATA:249,OP_SMALLINTEGER:250,OP_PUBKEYS:251,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};for(const t in vi)vi[vi[t]]=t;const Ii=vi,ki="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class Si{_chunks;parsed;rawBytesCache;hexCache;static fromASM(t){const e=[],i=t.split(" ");let r=0;for(;r<i.length;){const t=i[r];let s,n=0;if(t.startsWith("OP_")&&void 0!==Ii[t]&&(s=t,n=Ii[t]),"0"===t)n=0,e.push({op:n}),r+=1;else if("-1"===t)n=Ii.OP_1NEGATE,e.push({op:n}),r+=1;else if(void 0===s){let t=i[r];t.length%2!=0&&(t="0"+t);const s=Wt(t,"hex");if(Jt(s,"hex")!==t)throw new Error("invalid hex string in script");const a=s.length;a>=0&&a<Ii.OP_PUSHDATA1?n=a:a<Math.pow(2,8)?n=Ii.OP_PUSHDATA1:a<Math.pow(2,16)?n=Ii.OP_PUSHDATA2:a<Math.pow(2,32)&&(n=Ii.OP_PUSHDATA4),e.push({data:s,op:n}),r+=1}else n===Ii.OP_PUSHDATA1||n===Ii.OP_PUSHDATA2||n===Ii.OP_PUSHDATA4?(e.push({data:Wt(i[r+2],"hex"),op:n}),r+=3):(e.push({op:n}),r+=1)}return new Si(e)}static fromHex(t){if(0===t.length)return Si.fromBinary([]);if(t.length%2!=0)throw new Error("There is an uneven number of characters in the string which suggests it is not hex encoded.");if(!/^[0-9a-fA-F]+$/.test(t))throw new Error("Some elements in this string are not hex encoded.");const e=Wt(t,"hex"),i=Uint8Array.from(e);return new Si([],i,t.toLowerCase(),!1)}static fromBinary(t){const e=Uint8Array.from(t);return new Si([],e,void 0,!1)}constructor(t=[],e,i,r=!0){this._chunks=t,this.parsed=r,this.rawBytesCache=e,this.hexCache=i}get chunks(){return this.ensureParsed(),this._chunks}set chunks(t){this._chunks=t,this.parsed=!0,this.invalidateSerializationCaches()}ensureParsed(){this.parsed||(null!=this.rawBytesCache?this._chunks=Si.parseChunks(this.rawBytesCache):this._chunks=[],this.parsed=!0)}toASM(){let t="";for(let e=0;e<this.chunks.length;e++){const i=this.chunks[e];t+=this._chunkToString(i)}return t.slice(1)}toHex(){if(null!=this.hexCache)return this.hexCache;null==this.rawBytesCache&&(this.rawBytesCache=this.serializeChunksToBytes());const t=null!=ki?ki.from(this.rawBytesCache).toString("hex"):Jt(Array.from(this.rawBytesCache),"hex");return this.hexCache=t,t}toBinary(){return Array.from(this.toUint8Array())}toUint8Array(){return null==this.rawBytesCache&&(this.rawBytesCache=this.serializeChunksToBytes()),this.rawBytesCache}writeScript(t){return this.invalidateSerializationCaches(),this.chunks=this.chunks.concat(t.chunks),this}writeOpCode(t){return this.invalidateSerializationCaches(),this.chunks.push({op:t}),this}setChunkOpCode(t,e){return this.invalidateSerializationCaches(),this.chunks[t]={op:e},this}writeBn(t){if(this.invalidateSerializationCaches(),t.cmpn(0)===Ii.OP_0)this.chunks.push({op:Ii.OP_0});else if(0===t.cmpn(-1))this.chunks.push({op:Ii.OP_1NEGATE});else if(t.cmpn(1)>=0&&t.cmpn(16)<=0)this.chunks.push({op:t.toNumber()+Ii.OP_1-1});else{const e=t.toSm("little");this.writeBin(e)}return this}writeBin(t){let e;this.invalidateSerializationCaches();const i=t.length>0?t:void 0;if(t.length>0&&t.length<Ii.OP_PUSHDATA1)e=t.length;else if(0===t.length)e=Ii.OP_0;else if(t.length<Math.pow(2,8))e=Ii.OP_PUSHDATA1;else if(t.length<Math.pow(2,16))e=Ii.OP_PUSHDATA2;else{if(!(t.length<Math.pow(2,32)))throw new Error("You can't push that much data");e=Ii.OP_PUSHDATA4}return this.chunks.push({data:i,op:e}),this}writeNumber(t){return this.invalidateSerializationCaches(),this.writeBn(new a(t)),this}removeCodeseparators(){this.invalidateSerializationCaches();const t=[];for(let e=0;e<this.chunks.length;e++)this.chunks[e].op!==Ii.OP_CODESEPARATOR&&t.push(this.chunks[e]);return this.chunks=t,this}findAndDelete(t){this.invalidateSerializationCaches();const e=t.toUint8Array(),i=e.length;if(0===i)return this;const r=e[0]??0,s=t=>{if(t.op!==r)return!1;const s=t.data??[],n=s.length;if(0===n)return 1===i;if(t.op===Ii.OP_RETURN){if(i!==1+n)return!1;for(let t=0;t<n;t++)if(e[1+t]!==s[t])return!1;return!0}if(t.op<Ii.OP_PUSHDATA1){if(i!==1+n)return!1;for(let t=0;t<n;t++)if(e[1+t]!==s[t])return!1;return!0}if(t.op===Ii.OP_PUSHDATA1){if(i!==2+n)return!1;if(e[1]!==(255&n))return!1;for(let t=0;t<n;t++)if(e[2+t]!==s[t])return!1;return!0}if(t.op===Ii.OP_PUSHDATA2){if(i!==3+n)return!1;if(e[1]!==(255&n))return!1;if(e[2]!==(n>>8&255))return!1;for(let t=0;t<n;t++)if(e[3+t]!==s[t])return!1;return!0}if(t.op===Ii.OP_PUSHDATA4){if(i!==5+n)return!1;const t=n>>>0;if(e[1]!==(255&t))return!1;if(e[2]!==(t>>8&255))return!1;if(e[3]!==(t>>16&255))return!1;if(e[4]!==(t>>24&255))return!1;for(let t=0;t<n;t++)if(e[5+t]!==s[t])return!1;return!0}return!1};for(let t=0;t<this.chunks.length;)s(this.chunks[t])?this.chunks.splice(t,1):t++;return this}isPushOnly(){for(let t=0;t<this.chunks.length;t++)if(this.chunks[t].op>Ii.OP_16)return!1;return!0}isLockingScript(){throw new Error("Not implemented")}isUnlockingScript(){throw new Error("Not implemented")}static computeSerializedLength(t){let e=0;for(const i of t){if(e+=1,null==i.data)continue;const t=i.data.length;if(i.op===Ii.OP_RETURN){e+=t;break}i.op<Ii.OP_PUSHDATA1?e+=t:i.op===Ii.OP_PUSHDATA1?e+=1+t:i.op===Ii.OP_PUSHDATA2?e+=2+t:i.op===Ii.OP_PUSHDATA4&&(e+=4+t)}return e}serializeChunksToBytes(){const t=this.chunks,e=Si.computeSerializedLength(t),i=new Uint8Array(e);let r=0;for(let e=0;e<t.length;e++){const s=t[e];if(i[r++]=s.op,null!=s.data){if(s.op===Ii.OP_RETURN){i.set(s.data,r),r+=s.data.length;break}r=Si.writeChunkData(i,r,s.op,s.data)}}return i}invalidateSerializationCaches(){this.rawBytesCache=void 0,this.hexCache=void 0}static writeChunkData(t,e,i,r){const s=r.length;if(i<Ii.OP_PUSHDATA1)return t.set(r,e),e+s;if(i===Ii.OP_PUSHDATA1)return t[e++]=255&s,t.set(r,e),e+s;if(i===Ii.OP_PUSHDATA2)return t[e++]=255&s,t[e++]=s>>8&255,t.set(r,e),e+s;if(i===Ii.OP_PUSHDATA4){const i=s>>>0;return t[e++]=255&i,t[e++]=i>>8&255,t[e++]=i>>16&255,t[e++]=i>>24&255,t.set(r,e),e+s}return e}static parseChunks(t){const e=[],i=t.length;let r=0,s=0;for(;r<i;){const n=t[r++]??0;if(n===Ii.OP_RETURN&&0===s){e.push({op:n,data:Si.copyRange(t,r,i)});break}if(n===Ii.OP_IF||n===Ii.OP_NOTIF||n===Ii.OP_VERIF||n===Ii.OP_VERNOTIF?s++:n===Ii.OP_ENDIF&&s--,n>0&&n<Ii.OP_PUSHDATA1){const s=n,a=Math.min(r+s,i);e.push({data:Si.copyRange(t,r,a),op:n}),r=a}else if(n===Ii.OP_PUSHDATA1){const s=r<i?t[r++]??0:0,a=Math.min(r+s,i);e.push({data:Si.copyRange(t,r,a),op:n}),r=a}else if(n===Ii.OP_PUSHDATA2){const s=(t[r]??0)|(t[r+1]??0)<<8;r=Math.min(r+2,i);const a=Math.min(r+s,i);e.push({data:Si.copyRange(t,r,a),op:n}),r=a}else if(n===Ii.OP_PUSHDATA4){const s=((t[r]??0)|(t[r+1]??0)<<8|(t[r+2]??0)<<16|(t[r+3]??0)<<24)>>>0;r=Math.min(r+4,i);const a=Math.min(r+s,i);e.push({data:Si.copyRange(t,r,a),op:n}),r=a}else e.push({op:n})}return e}static copyRange(t,e,i){const r=Math.max(i-e,0),s=new Array(r);for(let i=0;i<r;i++)s[i]=t[e+i]??0;return s}_chunkToString(t){const e=t.op;let i="";return i=void 0===t.data?`${i} ${Ii[e]}`:`${i} ${jt(t.data)}`,i}}const Ei=new Uint8Array(0);class xi extends Be{static SIGHASH_ALL=1;static SIGHASH_NONE=2;static SIGHASH_SINGLE=3;static SIGHASH_CHRONICLE=32;static SIGHASH_FORKID=64;static SIGHASH_ANYONECANPAY=128;scope;static formatOTDA(t){const e=(t.scope&xi.SIGHASH_ANYONECANPAY)===xi.SIGHASH_ANYONECANPAY,i=(31&t.scope)===xi.SIGHASH_SINGLE,r=(31&t.scope)===xi.SIGHASH_NONE,s=(31&t.scope)===xi.SIGHASH_ALL||!i&&!r,n=new Si([...t.subscript.chunks]);n.findAndDelete((new Si).writeOpCode(Ii.OP_CODESEPARATOR));const a={sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,sequence:t.inputSequence,script:n.toBinary()},o=new se;function c(t){o.writeVarIntNum(t.length);for(const e of t)o.writeReverse(Wt(e.sourceTXID,"hex")),o.writeUInt32LE(e.sourceOutputIndex),o.writeVarIntNum(e.script.length),o.write(e.script),o.writeUInt32LE(e.sequence)}function h(t){o.writeVarIntNum(t.length);for(const e of t)o.writeUInt64LE(e.satoshis),o.writeVarIntNum(e.script.length),o.write(e.script)}o.writeInt32LE(t.transactionVersion);const u=(new Si).toBinary();if(e)e&&c([a]);else{const e=t.otherInputs.map(t=>({sourceTXID:t.sourceTXID??t.sourceTransaction?.id("hex")??"",sourceOutputIndex:t.sourceOutputIndex,sequence:i||r?0:t.sequence??4294967295,script:u}));e.splice(t.inputIndex,0,a),c(e)}if(s)h(t.outputs.map(t=>({satoshis:t.satoshis??0,script:t.lockingScript.toBinary()})));else if(i){const e=[];for(let i=0;i<t.inputIndex;i++)e.push({satoshis:-1,script:u});const i=t.outputs[t.inputIndex];void 0!==i&&e.push({satoshis:i.satoshis??0,script:i.lockingScript.toBinary()}),h(e)}else r&&h([]);return o.writeUInt32LE(t.lockTime),o.writeUInt32LE(t.scope>>>0),o.toUint8Array()}static formatBip143(t){const e=t.cache,i={sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,sequence:t.inputSequence},r=[...t.otherInputs];function s(e){const i=new se;if(void 0===e)for(const e of t.outputs){const t=e.satoshis??0;i.writeUInt64LE(t);const r=e.lockingScript?.toUint8Array()??Ei;i.writeVarIntNum(r.length),i.write(r)}else{const r=t.outputs[e];if(void 0===r)throw new Error(`Output at index ${e} does not exist`);const s=r.satoshis??0;i.writeUInt64LE(s);const n=r.lockingScript?.toUint8Array()??Ei;i.writeVarIntNum(n.length),i.write(n)}const r=i.toUint8Array();return Y(r)}r.splice(t.inputIndex,0,i);let n=new Array(32).fill(0),a=new Array(32).fill(0),o=new Array(32).fill(0);if(0===(t.scope&xi.SIGHASH_ANYONECANPAY)&&(null!=e?.hashPrevouts?n=e.hashPrevouts:(n=(()=>{const t=new se;for(const e of r){if(void 0===e.sourceTXID){if(null==e.sourceTransaction)throw new Error("Missing sourceTransaction for input");t.write(e.sourceTransaction.hash())}else t.writeReverse(Wt(e.sourceTXID,"hex"));t.writeUInt32LE(e.sourceOutputIndex)}const e=t.toUint8Array();return Y(e)})(),null!=e&&(e.hashPrevouts=n))),0===(t.scope&xi.SIGHASH_ANYONECANPAY)&&(31&t.scope)!==xi.SIGHASH_SINGLE&&(31&t.scope)!==xi.SIGHASH_NONE&&(null!=e?.hashSequence?a=e.hashSequence:(a=(()=>{const t=new se;for(const e of r){const i=e.sequence??4294967295;t.writeUInt32LE(i)}const e=t.toUint8Array();return Y(e)})(),null!=e&&(e.hashSequence=a))),(31&t.scope)!==xi.SIGHASH_SINGLE&&(31&t.scope)!==xi.SIGHASH_NONE)null!=e?.hashOutputsAll?o=e.hashOutputsAll:(o=s(),null!=e&&(e.hashOutputsAll=o));else if((31&t.scope)===xi.SIGHASH_SINGLE&&t.inputIndex<t.outputs.length){const i=t.inputIndex,r=e?.hashOutputsSingle?.get(i);null!=r?o=r:(o=s(i),null!=e&&(null==e.hashOutputsSingle&&(e.hashOutputsSingle=new Map),e.hashOutputsSingle.set(i,o)))}const c=new se;c.writeInt32LE(t.transactionVersion),c.write(n),c.write(a),c.writeReverse(Wt(t.sourceTXID,"hex")),c.writeUInt32LE(t.sourceOutputIndex);const h=t.subscript.toUint8Array();c.writeVarIntNum(h.length),c.write(h),c.writeUInt64LE(t.sourceSatoshis);const u=i.sequence;return c.writeUInt32LE(u),c.write(o),c.writeUInt32LE(t.lockTime),c.writeUInt32LE(t.scope>>>0),c.toUint8Array()}static format(t){return Array.from(this.formatBytes(t))}static formatBytes(t){const e=0!==(t.scope&xi.SIGHASH_FORKID),i=!0!==t.ignoreChronicle&&0!==(t.scope&xi.SIGHASH_CHRONICLE);return e&&!i?xi.formatBip143(t):!e||e&&i?xi.formatOTDA(t):new Uint8Array(0)}static fromChecksigFormat(t){if(0===t.length){const t=new a(1),e=new a(1);return new xi(t,e,1)}const e=t[t.length-1],i=t.slice(0,t.length-1),r=Be.fromDER(i);return new xi(r.r,r.s,e)}constructor(t,e,i){super(t,e),this.scope=i}hasLowS(){return!this.s.ltn(1)&&!this.s.gt(new a("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex"))}toChecksigFormat(){return[...this.toDER(),this.scope]}}class _i{curve;constructor(){this.curve=new Re}generateProof(t,e,i,r){const s=Je.fromRandom(),n=s.toPublicKey(),a=i.mul(s),o=this.computeChallenge(e,i,r,a,n);return{R:n,SPrime:a,z:s.add(o.mul(t)).umod(this.curve.n)}}verifyProof(t,e,i,r){const{R:s,SPrime:n,z:a}=r,o=this.computeChallenge(t,e,i,n,s),c=this.curve.g.mul(a),h=s.add(t.mul(o));if(!c.eq(h))return!1;const u=e.mul(a),d=n.add(i.mul(o));return!!u.eq(d)}computeChallenge(t,e,i,r,s){const n=[...t.encode(!0),...e.encode(!0),...i.encode(!0),...r.encode(!0),...s.encode(!0)],o=X(n);return new a(o).umod(this.curve.n)}}BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5");class Pi extends Si{isLockingScript(){return!0}isUnlockingScript(){return!1}}class Ai extends Si{isLockingScript(){return!1}isUnlockingScript(){return!0}}class Ni extends Error{txid;outputIndex;context;programCounter;stackState;altStackState;ifStackState;stackMem;altStackMem;constructor(t){const e=t.stackState.map(t=>null!=t&&void 0!==t.length?jt(t):null==t?"null/undef":"INVALID_STACK_ITEM").join(", "),i=t.altStackState.map(t=>null!=t&&void 0!==t.length?jt(t):null==t?"null/undef":"INVALID_STACK_ITEM").join(", "),r=`Context: ${t.context}, PC: ${t.programCounter}`,s=`Stack: [${e}] (len: ${t.stackState.length}, mem: ${t.stackMem})`,n=`AltStack: [${i}] (len: ${t.altStackState.length}, mem: ${t.altStackMem})`,a=`IfStack: [${t.ifStackState.join(", ")}]`;super(`Script evaluation error: ${t.message}\nTXID: ${t.txid}, OutputIdx: ${t.outputIndex}\n${r}\n${s}\n${n}\n${a}`),this.name=this.constructor.name,this.txid=t.txid,this.outputIndex=t.outputIndex,this.context=t.context,this.programCounter=t.programCounter,this.stackState=t.stackState.map(t=>t.slice()),this.altStackState=t.altStackState.map(t=>t.slice()),this.ifStackState=t.ifStackState.slice(),this.stackMem=t.stackMem,this.altStackMem=t.altStackMem}}const Oi=1073741824,Ti=Math.pow(2,31)-1,Ci=BigInt(Ti),Ri=Object.freeze(new a(-1).toScriptNum()),Bi=Object.freeze(Array.from({length:17},(t,e)=>Object.freeze(new a(e).toScriptNum())));function Li(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0}class Mi{sourceTXID;sourceOutputIndex;sourceSatoshis;lockingScript;transactionVersion;otherInputs;outputs;inputIndex;unlockingScript;inputSequence;lockTime;context;programCounter;lastCodeSeparator;stack;altStack;ifStack;memoryLimit;stackMem;altStackMem;isRelaxedOverride;sigHashCache;constructor(t){this.sourceTXID=t.sourceTXID,this.sourceOutputIndex=t.sourceOutputIndex,this.sourceSatoshis=t.sourceSatoshis,this.lockingScript=t.lockingScript,this.transactionVersion=t.transactionVersion,this.otherInputs=t.otherInputs,this.outputs=t.outputs,this.inputIndex=t.inputIndex,this.unlockingScript=t.unlockingScript,this.inputSequence=t.inputSequence,this.lockTime=t.lockTime,this.memoryLimit=t.memoryLimit??32e6,this.isRelaxedOverride=!0===t.isRelaxed,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0,this.sigHashCache={hashOutputsSingle:new Map},this.reset()}isRelaxed(){return this.isRelaxedOverride||this.transactionVersion>1}reset(){this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0,this.sigHashCache={hashOutputsSingle:new Map}}ensureStackMem(t){this.stackMem+t>this.memoryLimit&&this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}ensureAltStackMem(t){this.altStackMem+t>this.memoryLimit&&this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}pushStack(t){this.ensureStackMem(t.length),this.stack.push(t),this.stackMem+=t.length}pushStackCopy(t){this.ensureStackMem(t.length);const e=t.slice();this.stack.push(e),this.stackMem+=e.length}popStack(){0===this.stack.length&&this.scriptEvaluationError("Attempted to pop from an empty stack.");const t=this.stack.pop();return this.stackMem-=t.length,t}stackTop(t=-1){return(0===this.stack.length||this.stack.length<Math.abs(t)||t>=0&&t>=this.stack.length)&&this.scriptEvaluationError(`Stack underflow accessing element at index ${t}. Stack length is ${this.stack.length}.`),this.stack[this.stack.length+t]}pushAltStack(t){this.ensureAltStackMem(t.length),this.altStack.push(t),this.altStackMem+=t.length}popAltStack(){0===this.altStack.length&&this.scriptEvaluationError("Attempted to pop from an empty alt stack.");const t=this.altStack.pop();return this.altStackMem-=t.length,t}checkSignatureEncoding(t){if(0===t.length)return!0;if(!function(t){if(t.length<9||t.length>73)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-3)return!1;const e=t[2],i=t[3];if(2!==e)return!1;if(0===i)return!1;if(5+i>=t.length)return!1;const r=4+i,s=t[r],n=t[r+1];if(2!==s)return!1;if(0===n)return!1;if(128&t[4])return!1;if(i>1&&0===t[4]&&!(128&t[5]))return!1;const a=r+2;return!(128&t[a]||n>1&&0===t[a]&&!(128&t[a+1])||i+n+7!==t.length)}(t))return this.scriptEvaluationError("The signature format is invalid."),!1;try{const e=xi.fromChecksigFormat(t);if(!this.isRelaxed()&&!e.hasLowS())return this.scriptEvaluationError("The signature must have a low S value."),!1}catch(t){return this.scriptEvaluationError("The signature format is invalid."),!1}return!0}checkPublicKeyEncoding(t){if(0===t.length)return this.scriptEvaluationError("Public key is empty."),!1;if(t.length<33)return this.scriptEvaluationError("The public key is too short, it must be at least 33 bytes."),!1;if(4===t[0]){if(65!==t.length)return this.scriptEvaluationError("The non-compressed public key must be 65 bytes."),!1}else{if(2!==t[0]&&3!==t[0])return this.scriptEvaluationError("The public key is in an unknown format."),!1;if(33!==t.length)return this.scriptEvaluationError("The compressed public key must be 33 bytes."),!1}try{$e.fromDER(t)}catch(t){return this.scriptEvaluationError("The public key is in an unknown format."),!1}return!0}verifySignature(t,e,i){const r=xi.formatBytes({sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,transactionVersion:this.transactionVersion,otherInputs:this.otherInputs,outputs:this.outputs,inputIndex:this.inputIndex,subscript:i,inputSequence:this.inputSequence,lockTime:this.lockTime,scope:t.scope,cache:this.sigHashCache}),s=new a(Y(r));return Ke(s,t,e)}step(){if(this.stackMem>this.memoryLimit)return this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;if(this.altStackMem>this.memoryLimit)return this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;"UnlockingScript"===this.context&&this.programCounter>=this.unlockingScript.chunks.length&&(this.context="LockingScript",this.programCounter=0);const t="UnlockingScript"===this.context?this.unlockingScript:this.lockingScript;if(this.programCounter>=t.chunks.length)return!1;const e=t.chunks[this.programCounter],i=e.op;void 0===i&&this.scriptEvaluationError(`Missing opcode in ${this.context} at pc=${this.programCounter}.`),Array.isArray(e.data)&&e.data.length>Oi&&this.scriptEvaluationError(`Data push > 1073741824 bytes (pc=${this.programCounter}).`);const r=!this.ifStack.includes(!1);if(r&&i>=0&&i<=Ii.OP_PUSHDATA4)this.isRelaxed()||function(t){const e=t.data,i=t.op;return!(Array.isArray(e)&&(0===e.length?i!==Ii.OP_0:1===e.length&&e[0]>=1&&e[0]<=16?i!==Ii.OP_1+(e[0]-1):1===e.length&&129===e[0]?i!==Ii.OP_1NEGATE:e.length<=75?i!==e.length:e.length<=255?i!==Ii.OP_PUSHDATA1:e.length<=65535&&i!==Ii.OP_PUSHDATA2))}(e)||this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`),this.pushStack(Array.isArray(e.data)?e.data:[]);else if(r||i>=Ii.OP_IF&&i<=Ii.OP_ENDIF){let t,e,n,o,c,h,u,d,l,f,p,g,y,b,m,w,v,I,k,S,E,x,_,P,A,N;switch(i){case Ii.OP_VER:this.pushStackCopy(new a(this.transactionVersion).toScriptNum());break;case Ii.OP_SUBSTR:{this.stack.length<3&&this.scriptEvaluationError("OP_SUBSTR requires at least three items to be on the stack.");const e=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber(),i=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber();t=this.popStack();const r=t.length;(i<0||i>=r||e<0||e>r-i)&&this.scriptEvaluationError(`OP_SUBSTR offset (${i}) must be in range [0, ${r}) and length (${e}) must be in range [0, ${r-i}]`),this.pushStack(t.slice(i,i+e));break}case Ii.OP_LEFT:{this.stack.length<2&&this.scriptEvaluationError("OP_LEFT requires at least two items to be on the stack.");const e=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber();t=this.popStack();const i=t.length;(e<0||e>i)&&this.scriptEvaluationError(`OP_LEFT length (${e}) must be in range [0, ${i}]`),this.pushStack(t.slice(0,e));break}case Ii.OP_RIGHT:{this.stack.length<2&&this.scriptEvaluationError("OP_RIGHT requires at least two items to be on the stack.");const e=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber();t=this.popStack();const i=t.length;(e<0||e>i)&&this.scriptEvaluationError(`OP_RIGHT length (${e}) must be in range [0, ${i}]`),this.pushStack(t.slice(i-e,e));break}case Ii.OP_LSHIFTNUM:{this.stack.length<2&&this.scriptEvaluationError("OP_LSHIFTNUM requires at least two items to be on the stack.");const t=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();t<0&&this.scriptEvaluationError("OP_LSHIFTNUM bits to shift must not be negative.");const e=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt(),i=new a(e<<t);this.pushStack(i.toScriptNum());break}case Ii.OP_RSHIFTNUM:{this.stack.length<2&&this.scriptEvaluationError("OP_RSHIFTNUM requires at least two items to be on the stack.");const t=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();t<0&&this.scriptEvaluationError("OP_RSHIFTNUM bits to shift must not be negative.");const e=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();let i;i=new a(e<0?-(-e>>t):e>>t),this.pushStack(i.toScriptNum());break}case Ii.OP_1NEGATE:this.pushStackCopy(Ri);break;case Ii.OP_0:this.pushStackCopy(Bi[0]);break;case Ii.OP_1:case Ii.OP_2:case Ii.OP_3:case Ii.OP_4:case Ii.OP_5:case Ii.OP_6:case Ii.OP_7:case Ii.OP_8:case Ii.OP_9:case Ii.OP_10:case Ii.OP_11:case Ii.OP_12:case Ii.OP_13:case Ii.OP_14:case Ii.OP_15:case Ii.OP_16:g=i-(Ii.OP_1-1),this.pushStackCopy(Bi[g]);break;case Ii.OP_NOP:case Ii.OP_NOP1:case Ii.OP_NOP2:case Ii.OP_NOP3:case Ii.OP_NOP7:case Ii.OP_NOP8:case Ii.OP_NOP9:case Ii.OP_NOP10:case Ii.OP_NOP11:case Ii.OP_NOP12:case Ii.OP_NOP13:case Ii.OP_NOP14:case Ii.OP_NOP15:case Ii.OP_NOP16:case Ii.OP_NOP17:case Ii.OP_NOP18:case Ii.OP_NOP19:case Ii.OP_NOP20:case Ii.OP_NOP21:case Ii.OP_NOP22:case Ii.OP_NOP23:case Ii.OP_NOP24:case Ii.OP_NOP25:case Ii.OP_NOP26:case Ii.OP_NOP27:case Ii.OP_NOP28:case Ii.OP_NOP29:case Ii.OP_NOP30:case Ii.OP_NOP31:case Ii.OP_NOP32:case Ii.OP_NOP33:case Ii.OP_NOP34:case Ii.OP_NOP35:case Ii.OP_NOP36:case Ii.OP_NOP37:case Ii.OP_NOP38:case Ii.OP_NOP39:case Ii.OP_NOP40:case Ii.OP_NOP41:case Ii.OP_NOP42:case Ii.OP_NOP43:case Ii.OP_NOP44:case Ii.OP_NOP45:case Ii.OP_NOP46:case Ii.OP_NOP47:case Ii.OP_NOP48:case Ii.OP_NOP49:case Ii.OP_NOP50:case Ii.OP_NOP51:case Ii.OP_NOP52:case Ii.OP_NOP53:case Ii.OP_NOP54:case Ii.OP_NOP55:case Ii.OP_NOP56:case Ii.OP_NOP57:case Ii.OP_NOP58:case Ii.OP_NOP59:case Ii.OP_NOP60:case Ii.OP_NOP61:case Ii.OP_NOP62:case Ii.OP_NOP63:case Ii.OP_NOP64:case Ii.OP_NOP65:case Ii.OP_NOP66:case Ii.OP_NOP67:case Ii.OP_NOP68:case Ii.OP_NOP69:case Ii.OP_NOP70:case Ii.OP_NOP71:case Ii.OP_NOP72:case Ii.OP_NOP73:case Ii.OP_NOP77:break;case Ii.OP_VERIF:case Ii.OP_VERNOTIF:b=!1,r&&(this.stack.length<1&&this.scriptEvaluationError("OP_VERIF and OP_VERNOTIF require at least one item on the stack when they are used!"),n=new a(this.transactionVersion).toScriptNum(),e=this.popStack(),b=Li(e,n),i===Ii.OP_VERNOTIF&&(b=!b)),this.ifStack.push(b);break;case Ii.OP_IF:case Ii.OP_NOTIF:b=!1,r&&(this.stack.length<1&&this.scriptEvaluationError("OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),t=this.popStack(),b=this.castToBool(t),i===Ii.OP_NOTIF&&(b=!b)),this.ifStack.push(b);break;case Ii.OP_ELSE:0===this.ifStack.length&&this.scriptEvaluationError("OP_ELSE requires a preceeding OP_IF."),this.ifStack[this.ifStack.length-1]=!this.ifStack[this.ifStack.length-1];break;case Ii.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop();break;case Ii.OP_VERIFY:this.stack.length<1&&this.scriptEvaluationError("OP_VERIFY requires at least one item to be on the stack."),e=this.stackTop(),b=this.castToBool(e),b||this.scriptEvaluationError("OP_VERIFY requires the top stack value to be truthy."),this.popStack();break;case Ii.OP_RETURN:"UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.ifStack=[],this.programCounter--;break;case Ii.OP_TOALTSTACK:this.stack.length<1&&this.scriptEvaluationError("OP_TOALTSTACK requires at oeast one item to be on the stack."),this.pushAltStack(this.popStack());break;case Ii.OP_FROMALTSTACK:this.altStack.length<1&&this.scriptEvaluationError("OP_FROMALTSTACK requires at least one item to be on the stack."),this.pushStack(this.popAltStack());break;case Ii.OP_2DROP:this.stack.length<2&&this.scriptEvaluationError("OP_2DROP requires at least two items to be on the stack."),this.popStack(),this.popStack();break;case Ii.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),e=this.stackTop(-2),n=this.stackTop(-1),this.pushStackCopy(e),this.pushStackCopy(n);break;case Ii.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),e=this.stackTop(-3),n=this.stackTop(-2),o=this.stackTop(-1),this.pushStackCopy(e),this.pushStackCopy(n),this.pushStackCopy(o);break;case Ii.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),e=this.stackTop(-4),n=this.stackTop(-3),this.pushStackCopy(e),this.pushStackCopy(n);break;case Ii.OP_2ROT:{this.stack.length<6&&this.scriptEvaluationError("OP_2ROT requires at least six items to be on the stack.");const t=this.popStack(),e=this.popStack(),i=this.popStack(),r=this.popStack(),s=this.popStack(),n=this.popStack();this.pushStack(r),this.pushStack(i),this.pushStack(e),this.pushStack(t),this.pushStack(n),this.pushStack(s);break}case Ii.OP_2SWAP:{this.stack.length<4&&this.scriptEvaluationError("OP_2SWAP requires at least four items to be on the stack.");const t=this.popStack(),e=this.popStack(),i=this.popStack(),r=this.popStack();this.pushStack(e),this.pushStack(t),this.pushStack(r),this.pushStack(i);break}case Ii.OP_IFDUP:this.stack.length<1&&this.scriptEvaluationError("OP_IFDUP requires at least one item to be on the stack."),e=this.stackTop(),this.castToBool(e)&&this.pushStackCopy(e);break;case Ii.OP_DEPTH:this.pushStack(new a(this.stack.length).toScriptNum());break;case Ii.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),this.popStack();break;case Ii.OP_DUP:this.stack.length<1&&this.scriptEvaluationError("OP_DUP requires at least one item to be on the stack."),this.pushStackCopy(this.stackTop());break;case Ii.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),n=this.popStack(),this.popStack(),this.pushStack(n);break;case Ii.OP_OVER:this.stack.length<2&&this.scriptEvaluationError("OP_OVER requires at least two items to be on the stack."),this.pushStackCopy(this.stackTop(-2));break;case Ii.OP_PICK:case Ii.OP_ROLL:{this.stack.length<2&&this.scriptEvaluationError(`${Ii[i]} requires at least two items to be on the stack.`),d=a.fromScriptNum(this.popStack(),!this.isRelaxed());const t=d.toBigInt();(t<0n||t>=BigInt(this.stack.length))&&this.scriptEvaluationError(`${Ii[i]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);const e=Number(t),r=this.stack[this.stack.length-1-e];i===Ii.OP_ROLL?(this.stack.splice(this.stack.length-1-e,1),this.stackMem-=r.length,this.pushStack(r)):this.pushStackCopy(r);break}case Ii.OP_ROT:this.stack.length<3&&this.scriptEvaluationError("OP_ROT requires at least three items to be on the stack."),u=this.popStack(),h=this.popStack(),c=this.popStack(),this.pushStack(h),this.pushStack(u),this.pushStack(c);break;case Ii.OP_SWAP:this.stack.length<2&&this.scriptEvaluationError("OP_SWAP requires at least two items to be on the stack."),h=this.popStack(),c=this.popStack(),this.pushStack(h),this.pushStack(c);break;case Ii.OP_TUCK:this.stack.length<2&&this.scriptEvaluationError("OP_TUCK requires at least two items to be on the stack."),e=this.stackTop(-1),this.ensureStackMem(e.length),this.stack.splice(this.stack.length-2,0,e.slice()),this.stackMem+=e.length;break;case Ii.OP_SIZE:this.stack.length<1&&this.scriptEvaluationError("OP_SIZE requires at least one item to be on the stack."),this.pushStack(new a(this.stackTop().length).toScriptNum());break;case Ii.OP_AND:case Ii.OP_OR:case Ii.OP_XOR:{this.stack.length<2&&this.scriptEvaluationError(`${Ii[i]} requires at least two items on the stack.`),n=this.popStack(),e=this.popStack(),e.length!==n.length&&this.scriptEvaluationError(`${Ii[i]} requires the top two stack items to be the same size.`);const t=new Array(e.length);for(let r=0;r<e.length;r++)i===Ii.OP_AND?t[r]=e[r]&n[r]:i===Ii.OP_OR?t[r]=e[r]|n[r]:t[r]=e[r]^n[r];this.pushStack(t);break}case Ii.OP_INVERT:{this.stack.length<1&&this.scriptEvaluationError("OP_INVERT requires at least one item to be on the stack."),t=this.popStack();const e=new Array(t.length);for(let i=0;i<t.length;i++)e[i]=255&~t[i];this.pushStack(e);break}case Ii.OP_LSHIFT:case Ii.OP_RSHIFT:{this.stack.length<2&&this.scriptEvaluationError(`${Ii[i]} requires at least two items to be on the stack.`),f=a.fromScriptNum(this.popStack(),!this.isRelaxed()),e=this.popStack();const t=f.toBigInt();if(t<0n&&this.scriptEvaluationError(`${Ii[i]} requires the top item on the stack not to be negative.`),0===e.length){this.pushStack([]);break}let r;l=new a(e),r=i===Ii.OP_LSHIFT?l.ushln(t):l.ushrn(t);const s=r.toArray("be",e.length);this.pushStack(s);break}case Ii.OP_EQUAL:case Ii.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${Ii[i]} requires at least two items to be on the stack.`),n=this.popStack(),e=this.popStack(),b=Li(e,n),this.pushStack(b?[1]:[]),i===Ii.OP_EQUALVERIFY&&(b||this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."),this.popStack());break;case Ii.OP_1ADD:case Ii.OP_1SUB:case Ii.OP_2MUL:case Ii.OP_2DIV:case Ii.OP_NEGATE:case Ii.OP_ABS:case Ii.OP_NOT:case Ii.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${Ii[i]} requires at least one item to be on the stack.`),d=a.fromScriptNum(this.popStack(),!this.isRelaxed()),i){case Ii.OP_1ADD:d=d.add(new a(1));break;case Ii.OP_1SUB:d=d.sub(new a(1));break;case Ii.OP_2MUL:d=d.mul(new a(2));break;case Ii.OP_2DIV:d=d.div(new a(2));break;case Ii.OP_NEGATE:d=d.neg();break;case Ii.OP_ABS:d.isNeg()&&(d=d.neg());break;case Ii.OP_NOT:d=new a(0===d.cmpn(0)?1:0);break;case Ii.OP_0NOTEQUAL:d=new a(0!==d.cmpn(0)?1:0)}this.pushStack(d.toScriptNum());break;case Ii.OP_ADD:case Ii.OP_SUB:case Ii.OP_MUL:case Ii.OP_DIV:case Ii.OP_MOD:case Ii.OP_BOOLAND:case Ii.OP_BOOLOR:case Ii.OP_NUMEQUAL:case Ii.OP_NUMEQUALVERIFY:case Ii.OP_NUMNOTEQUAL:case Ii.OP_LESSTHAN:case Ii.OP_GREATERTHAN:case Ii.OP_LESSTHANOREQUAL:case Ii.OP_GREATERTHANOREQUAL:case Ii.OP_MIN:case Ii.OP_MAX:{this.stack.length<2&&this.scriptEvaluationError(`${Ii[i]} requires at least two items to be on the stack.`),n=this.popStack(),e=this.popStack(),f=a.fromScriptNum(n,!this.isRelaxed()),l=a.fromScriptNum(e,!this.isRelaxed());let t=0;switch(i){case Ii.OP_MUL:t=l.byteLength()+f.byteLength();break;case Ii.OP_ADD:case Ii.OP_SUB:t=Math.max(l.byteLength(),f.byteLength())+1;break;default:t=Math.max(l.byteLength(),f.byteLength())}this.ensureStackMem(t);let r=new a(0);switch(i){case Ii.OP_ADD:r=l.add(f);break;case Ii.OP_SUB:r=l.sub(f);break;case Ii.OP_MUL:r=l.mul(f);break;case Ii.OP_DIV:0===f.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),r=l.div(f);break;case Ii.OP_MOD:0===f.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),r=l.mod(f);break;case Ii.OP_BOOLAND:r=new a(0!==l.cmpn(0)&&0!==f.cmpn(0)?1:0);break;case Ii.OP_BOOLOR:r=new a(0!==l.cmpn(0)||0!==f.cmpn(0)?1:0);break;case Ii.OP_NUMEQUAL:case Ii.OP_NUMEQUALVERIFY:r=new a(0===l.cmp(f)?1:0);break;case Ii.OP_NUMNOTEQUAL:r=new a(0!==l.cmp(f)?1:0);break;case Ii.OP_LESSTHAN:r=new a(l.cmp(f)<0?1:0);break;case Ii.OP_GREATERTHAN:r=new a(l.cmp(f)>0?1:0);break;case Ii.OP_LESSTHANOREQUAL:r=new a(l.cmp(f)<=0?1:0);break;case Ii.OP_GREATERTHANOREQUAL:r=new a(l.cmp(f)>=0?1:0);break;case Ii.OP_MIN:r=l.cmp(f)<0?l:f;break;case Ii.OP_MAX:r=l.cmp(f)>0?l:f}this.pushStack(r.toScriptNum()),i===Ii.OP_NUMEQUALVERIFY&&(this.castToBool(this.stackTop())||this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."),this.popStack());break}case Ii.OP_WITHIN:this.stack.length<3&&this.scriptEvaluationError("OP_WITHIN requires at least three items to be on the stack."),p=a.fromScriptNum(this.popStack(),!this.isRelaxed()),f=a.fromScriptNum(this.popStack(),!this.isRelaxed()),l=a.fromScriptNum(this.popStack(),!this.isRelaxed()),b=l.cmp(f)>=0&&l.cmp(p)<0,this.pushStack(b?[1]:[]);break;case Ii.OP_RIPEMD160:case Ii.OP_SHA1:case Ii.OP_SHA256:case Ii.OP_HASH160:case Ii.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${Ii[i]} requires at least one item to be on the stack.`),t=this.popStack();let e=[];i===Ii.OP_RIPEMD160?(s=t,e=(new $).update(s,void 0).digest()):i===Ii.OP_SHA1?e=(t=>(new z).update(t,void 0).digest())(t):i===Ii.OP_SHA256?e=X(t):i===Ii.OP_HASH160?e=J(t):i===Ii.OP_HASH256&&(e=Y(t)),this.pushStack(e);break}case Ii.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case Ii.OP_CHECKSIG:case Ii.OP_CHECKSIGVERIFY:if(this.stack.length<2&&this.scriptEvaluationError(`${Ii[i]} requires at least two items to be on the stack.`),I=this.popStack(),v=this.popStack(),this.checkSignatureEncoding(v)&&this.checkPublicKeyEncoding(I)||this.scriptEvaluationError(`${Ii[i]} requires correct encoding for the public key and signature.`),m=!1,v.length>0)try{k=xi.fromChecksigFormat(v);const t=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);w=new Si(t),w.findAndDelete((new Si).writeBin(v)),S=$e.fromDER(I),m=this.verifySignature(k,S,w)}catch(t){m=!1}this.pushStack(m?[1]:[]),i===Ii.OP_CHECKSIGVERIFY&&(m||this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."),this.popStack());break;case Ii.OP_CHECKMULTISIG:case Ii.OP_CHECKMULTISIGVERIFY:{E=1,this.stack.length<E&&this.scriptEvaluationError(`${Ii[i]} requires at least 1 item for nKeys.`);const t=a.fromScriptNum(this.stackTop(-E),!this.isRelaxed()).toBigInt();(t<0n||t>Ci)&&this.scriptEvaluationError(`${Ii[i]} requires a key count between 0 and ${Ti}.`),P=Number(t);const e=P;x=++E,E+=P,this.stack.length<E&&this.scriptEvaluationError(`${Ii[i]} stack too small for nKeys and keys. Need ${E}, have ${this.stack.length}.`);const r=a.fromScriptNum(this.stackTop(-E),!this.isRelaxed()).toBigInt();(r<0n||r>BigInt(P))&&this.scriptEvaluationError(`${Ii[i]} requires the number of signatures to be no greater than the number of keys.`),A=Number(r);const s=A;_=++E,E+=A,this.stack.length<E&&this.scriptEvaluationError(`${Ii[i]} stack too small for N, keys, M, sigs, and dummy. Need ${E}, have ${this.stack.length}.`);const n=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);w=new Si(n);for(let t=0;t<A;t++)v=this.stackTop(-_-t),w.findAndDelete((new Si).writeBin(v));for(m=!0;m&&A>0;){if(0===P){m=!1;break}if(v=this.stackTop(-_),I=this.stackTop(-x),this.checkSignatureEncoding(v)&&this.checkPublicKeyEncoding(I)||this.scriptEvaluationError(`${Ii[i]} requires correct encoding for the public key and signature.`),N=!1,v.length>0)try{k=xi.fromChecksigFormat(v),S=$e.fromDER(I),N=this.verifySignature(k,S,w)}catch(t){N=!1}N&&(_++,A--),x++,P--,A>P&&(m=!1)}let o=1+e+1+s+1-1;for(;o>0;)this.popStack(),o--;this.stack.length<1&&this.scriptEvaluationError(`${Ii[i]} requires an extra item (dummy) to be on the stack.`);const c=this.popStack();!this.isRelaxed()&&c.length>0&&this.scriptEvaluationError(`${Ii[i]} requires the extra stack item (dummy) to be empty.`),this.pushStack(m?[1]:[]),i===Ii.OP_CHECKMULTISIGVERIFY&&(m||this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),this.popStack());break}case Ii.OP_CAT:{this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),n=this.popStack(),e=this.popStack();const t=e.concat(n);t.length>Oi&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),this.pushStack(t);break}case Ii.OP_SPLIT:{this.stack.length<2&&this.scriptEvaluationError("OP_SPLIT requires at least two items to be on the stack.");const t=this.popStack(),e=this.popStack(),i=a.fromScriptNum(t,!this.isRelaxed()).toBigInt();(i<0n||i>BigInt(e.length))&&this.scriptEvaluationError("OP_SPLIT requires the first stack item to be a non-negative number less than or equal to the size of the second-from-top stack item.");const r=Number(i);this.pushStack(e.slice(0,r)),this.pushStack(e.slice(r));break}case Ii.OP_NUM2BIN:{this.stack.length<2&&this.scriptEvaluationError("OP_NUM2BIN requires at least two items to be on the stack.");const t=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();(t>BigInt(Oi)||t<0n)&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes or negative size."),y=Number(t);let e=this.popStack();if(e=ae(e),e.length>y&&this.scriptEvaluationError("OP_NUM2BIN requires that the size expressed in the top stack item is large enough to hold the value expressed in the second-from-top stack item."),e.length===y){this.pushStack(e);break}const i=new Array(y).fill(0);let r=0;e.length>0&&(r=128&e[e.length-1],e[e.length-1]&=127);for(let t=0;t<e.length;t++)i[t]=e[t];0!==r&&(i[y-1]|=128),this.pushStack(i);break}case Ii.OP_BIN2NUM:{this.stack.length<1&&this.scriptEvaluationError("OP_BIN2NUM requires at least one item to be on the stack."),e=this.popStack();const t=ae(e);(function(t,e=Number.MAX_SAFE_INTEGER){return!(t.length>e||t.length>0&&!(127&t[t.length-1]||!(t.length<=1)&&128&t[t.length-2]))})(t)||this.scriptEvaluationError("OP_BIN2NUM requires that the resulting number is valid."),this.pushStack(t);break}default:this.scriptEvaluationError(`Invalid opcode ${i} (pc=${this.programCounter}).`)}}var s;return this.programCounter++,!0}validate(){for(this.isRelaxed()||this.unlockingScript.isPushOnly()||this.scriptEvaluationError("Unlocking scripts can only contain push operations, and no other opcodes.");this.step()&&!("LockingScript"===this.context&&this.programCounter>=this.lockingScript.chunks.length););return this.ifStack.length>0&&this.scriptEvaluationError("Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the script."),this.isRelaxed()||1!==this.stack.length&&this.scriptEvaluationError(`The clean stack rule requires exactly one item to be on the stack after script execution, found ${this.stack.length}.`),0===this.stack.length?this.scriptEvaluationError("The top stack element must be truthy after script evaluation (stack is empty)."):this.castToBool(this.stackTop())||this.scriptEvaluationError("The top stack element must be truthy after script evaluation."),!0}castToBool(t){if(0===t.length)return!1;for(let e=0;e<t.length;e++)if(0!==t[e])return!(e===t.length-1&&128===t[e]);return!1}scriptEvaluationError(t){throw new Ni({message:t,txid:this.sourceTXID,outputIndex:this.sourceOutputIndex,context:this.context,programCounter:this.programCounter,stackState:this.stack,altStackState:this.altStack,ifStackState:this.ifStack,stackMem:this.stackMem,altStackMem:this.altStackMem})}}class Fi{lock(t){let e;if("string"==typeof t){const i=re(t);if(0!==i.prefix[0]&&111!==i.prefix[0])throw new Error("only P2PKH is supported");e=i.data}else e=t;if(20!==e.length)throw new Error("P2PKH hash length must be 20 bytes");return new Pi([{op:Ii.OP_DUP},{op:Ii.OP_HASH160},{op:e.length,data:e},{op:Ii.OP_EQUALVERIFY},{op:Ii.OP_CHECKSIG}])}unlock(t,e="all",i=!1,r,s){return{sign:async(n,a)=>{let o=xi.SIGHASH_FORKID;"all"===e&&(o|=xi.SIGHASH_ALL),"none"===e&&(o|=xi.SIGHASH_NONE),"single"===e&&(o|=xi.SIGHASH_SINGLE),i&&(o|=xi.SIGHASH_ANYONECANPAY);const c=n.inputs[a],h=n.inputs.filter((t,e)=>e!==a),u=c.sourceTXID??c.sourceTransaction?.id("hex");if(null==u||void 0===u)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(""===u)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(r||=c.sourceTransaction?.outputs[c.sourceOutputIndex].satoshis,null==r||void 0===r)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(s||=c.sourceTransaction?.outputs[c.sourceOutputIndex].lockingScript,null==s)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");const d=xi.format({sourceTXID:u,sourceOutputIndex:he(c.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:r,transactionVersion:n.version,otherInputs:h,inputIndex:a,outputs:n.outputs,inputSequence:he(c.sequence,"input.sequence must have value"),subscript:s,lockTime:n.lockTime,scope:o}),l=t.sign(X(d)),f=new xi(l.r,l.s,o).toChecksigFormat(),p=t.toPublicKey().encode(!0);return new Ai([{op:f.length,data:f},{op:p.length,data:p}])},estimateLength:async()=>108}}}const Ui=t=>0===t.length||1===t.length&&0===t[0]?{op:0}:1===t.length&&t[0]>0&&t[0]<=16?{op:80+t[0]}:1===t.length&&129===t[0]?{op:79}:t.length<=75?{op:t.length,data:t}:t.length<=255?{op:76,data:t}:t.length<=65535?{op:77,data:t}:{op:78,data:t};class Di{wallet;originator;static decode(t,e="before"){let i,r;if("before"===e)i=$e.fromString(jt(he(t.chunks[0].data,"script.chunks[0].data must have value"))),r=2;else{const e=t.chunks.length-1;if(t.chunks[e].op!==Ii.OP_CHECKSIG)throw new Error("Expected OP_CHECKSIG at the end of the script");i=$e.fromString(jt(he(t.chunks[e-1].data,"public key chunk data must have value"))),r=0}const s=[];for(let e=r;e<t.chunks.length;e++){const i=t.chunks[e+1]?.op;let r=t.chunks[e].data??[];if(0===r.length&&(t.chunks[e].op>=80&&t.chunks[e].op<=95?r=[t.chunks[e].op-80]:0===t.chunks[e].op?r=[0]:79===t.chunks[e].op&&(r=[129])),s.push(r),i===Ii.OP_DROP||i===Ii.OP_2DROP)break}return{fields:s,lockingPublicKey:i}}constructor(t,e){this.wallet=t,this.originator=e}async lock(t,e,i,r,s=!1,n=!0,a="before"){const{publicKey:o}=await this.wallet.getPublicKey({protocolID:e,keyID:i,counterparty:r,forSelf:s},this.originator),c=[],h=[];if(c.push({op:o.length/2,data:Wt(o,"hex")}),c.push({op:Ii.OP_CHECKSIG}),n){const s=t.reduce((t,e)=>[...t,...e],[]),{signature:n}=await this.wallet.createSignature({data:s,protocolID:e,keyID:i,counterparty:r},this.originator);t.push(n)}for(const e of t)h.push(Ui(e));let u=t.length;for(;u>1;)h.push({op:Ii.OP_2DROP}),u-=2;return 0!==u&&h.push({op:Ii.OP_DROP}),new Pi("before"===a?[...c,...h]:[...h,...c])}unlock(t,e,i,r="all",s=!1,n,a){return{sign:async(o,c)=>{let h=xi.SIGHASH_FORKID;"all"===r&&(h|=xi.SIGHASH_ALL),"none"===r&&(h|=xi.SIGHASH_NONE),"single"===r&&(h|=xi.SIGHASH_SINGLE),s&&(h|=xi.SIGHASH_ANYONECANPAY);const u=o.inputs[c],d=o.inputs.filter((t,e)=>e!==c),l=u.sourceTXID??u.sourceTransaction?.id("hex");if(null==l||void 0===l)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(n||=u.sourceTransaction?.outputs[u.sourceOutputIndex].satoshis,null==n||void 0===n)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(a||=u.sourceTransaction?.outputs[u.sourceOutputIndex].lockingScript,null==a)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");const f=xi.format({sourceTXID:l,sourceOutputIndex:he(u.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:n,transactionVersion:o.version,otherInputs:d,inputIndex:c,outputs:o.outputs,inputSequence:u.sequence??4294967295,subscript:a,lockTime:o.lockTime,scope:h}),p=X(f),{signature:g}=await this.wallet.createSignature({data:p,protocolID:t,keyID:e,counterparty:i},this.originator),y=Be.fromDER([...g]),b=new xi(y.r,y.s,h).toChecksigFormat();return new Ai([{op:b.length,data:b}])},estimateLength:async()=>73}}}class Hi{value;constructor(t){this.value=t}async computeFee(t){const e=t=>t>2**32?9:t>65536?5:t>253?3:1;let i=4;i+=e(t.inputs.length);for(let r=0;r<t.inputs.length;r++){const s=t.inputs[r];let n;if(i+=40,"object"==typeof s.unlockingScript)n=s.unlockingScript.toBinary().length;else{if("object"!=typeof s.unlockingScriptTemplate)throw new Error("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");n=await s.unlockingScriptTemplate.estimateLength(t,r)}i+=e(n),i+=n}i+=e(t.outputs.length);for(const r of t.outputs){i+=8;const t=r.lockingScript.toBinary().length;i+=e(t),i+=t}return i+=4,Math.ceil(i/1e3*this.value)}}class qi extends Hi{static ARC_POLICY_URL="https://arc.gorillapool.io/v1/policy";static instance=null;cachedRate=null;cacheTimestamp=0;cacheValidityMs;constructor(t=3e5){super(100),this.cacheValidityMs=t}static getInstance(t=3e5){return qi.instance||(qi.instance=new qi(t)),qi.instance}async fetchFeeRate(){const t=Date.now();if(null!==this.cachedRate&&t-this.cacheTimestamp<this.cacheValidityMs)return this.cachedRate;try{const e=await fetch(qi.ARC_POLICY_URL);if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const i=await e.json();if(!i.policy?.miningFee||"number"!=typeof i.policy.miningFee.satoshis||"number"!=typeof i.policy.miningFee.bytes)throw new Error("Invalid policy response format");const r=i.policy.miningFee.satoshis/i.policy.miningFee.bytes*1e3;return this.cachedRate=r,this.cacheTimestamp=t,r}catch(t){return null!==this.cachedRate?(console.warn("Failed to fetch live fee rate, using cached value:",t),this.cachedRate):(console.warn("Failed to fetch live fee rate, using default 100 sat/kb:",t),100)}}async computeFee(t){const e=await this.fetchFeeRate();return this.value=e,super.computeFee(t)}}class Vi{https;constructor(t){this.https=t}async request(t,e){return await new Promise((i,r)=>{const s=this.https.request(t,e,t=>{let e="";t.on("data",t=>{e+=t}),t.on("end",()=>{const r=t.statusCode>=200&&t.statusCode<=299,s=t.headers["content-type"],n=""!==e&&"string"==typeof s&&s.startsWith("application/json")?JSON.parse(e):e;i({status:t.statusCode,statusText:t.statusMessage,ok:r,data:n})})});s.on("error",t=>{r(t)}),null!==e.data&&void 0!==e.data&&s.write(JSON.stringify(e.data)),s.end()})}}class Ki{fetch;constructor(t){this.fetch=t}async request(t,e){const i={method:e.method,headers:e.headers,body:JSON.stringify(e.data)},r=await this.fetch(t,i),s=r.headers.get("Content-Type"),n=s?.startsWith("application/json")?await r.json():await r.text();return{ok:r.ok,status:r.status,statusText:r.statusText,data:n}}}function $i(){const t={async request(...t){throw new Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new Ki(window.fetch.bind(window));if("undefined"==typeof require)return t;try{const t=require("https");return new Vi(t)}catch(e){return t}}function ji(){return`ts-sdk-${jt(We(16))}`}class zi{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(t,e){if(this.URL=t,"string"==typeof e)this.apiKey=e,this.httpClient=$i(),this.deploymentId=ji(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const t=e??{},{apiKey:i,deploymentId:r,httpClient:s,callbackToken:n,callbackUrl:a,headers:o}=t;this.apiKey=i,this.httpClient=s??$i(),this.deploymentId=r??ji(),this.callbackToken=n,this.callbackUrl=a,this.headers=o}}requestHeaders(){const t={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(null!=this.apiKey&&""!==this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),null!=this.callbackUrl&&""!==this.callbackUrl&&(t["X-CallbackUrl"]=this.callbackUrl),null!=this.callbackToken&&""!==this.callbackToken&&(t["X-CallbackToken"]=this.callbackToken),null!=this.headers)for(const e in this.headers)t[e]=this.headers[e];return t}async broadcast(t){let e;try{e=t.toHexEF()}catch(i){if("All inputs must have source transactions when serializing to EF format"!==i.message)throw i;e=t.toHex()}const i={method:"POST",headers:this.requestHeaders(),data:{rawTx:e}};try{const t=await this.httpClient.request(`${this.URL}/v1/tx`,i);if(t.ok){const{txid:e,extraInfo:i,txStatus:r,competingTxs:s}=t.data,n=["DOUBLE_SPEND_ATTEMPTED","REJECTED","INVALID","MALFORMED","MINED_IN_STALE_BLOCK"],a=i?.toUpperCase().includes("ORPHAN")||r?.toUpperCase().includes("ORPHAN");if(n.includes(r?.toUpperCase())||a){const t={status:"error",code:r??"UNKNOWN",txid:e,description:`${r??""} ${i??""}`.trim()};return null!=s&&(t.more={competingTxs:s}),t}const o={status:"success",txid:e,message:`${r} ${i}`};return null!=s&&(o.competingTxs=s),o}{const e=typeof t.status,i={status:"error",code:"number"===e||"string"===e?t.status.toString():"ERR_UNKNOWN",description:"Unknown error"};let r=t.data;if("string"==typeof r)try{r=JSON.parse(t.data)}catch{}return"object"==typeof r&&(null!==r&&(i.more=r),null!=r&&"string"==typeof r.txid&&(i.txid=r.txid),null!=r&&"detail"in r&&"string"==typeof r.detail&&(i.description=r.detail)),i}}catch(t){return{status:"error",code:"500",description:"string"==typeof t.message?t.message:"Internal Server Error"}}}async broadcastMany(t){const e=t.map(t=>{try{return{rawTx:t.toHexEF()}}catch(e){if("All inputs must have source transactions when serializing to EF format"===e.message)return{rawTx:t.toHex()};throw e}}),i={method:"POST",headers:this.requestHeaders(),data:e};try{return(await this.httpClient.request(`${this.URL}/v1/txs`,i)).data}catch(e){const i={status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"};return t.map(()=>i)}}}class Wi{network;apiKey;URL;httpClient;constructor(t="main",e={}){const{apiKey:i,httpClient:r}=e;this.network=t,this.URL=`https://api.whatsonchain.com/v1/bsv/${t}`,this.httpClient=r??$i(),this.apiKey=i??""}async isValidRootForHeight(t,e){const i={method:"GET",headers:this.getHttpHeaders()},r=await this.httpClient.request(`${this.URL}/block/${e}/header`,i);if(r.ok){const{merkleroot:e}=r.data;return e===t}if(404===r.status)return!1;throw new Error(`Failed to verify merkleroot for height ${e} because of an error: ${JSON.stringify(r.data)} `)}async currentHeight(){try{const t={method:"GET",headers:this.getHttpHeaders()},e=await this.httpClient.request(`${this.URL}/block/headers`,t);if(e.ok)return e.data[0].height;throw new Error(`Failed to get current height because of an error: ${JSON.stringify(e.data)} `)}catch(t){throw new Error(`Failed to get current height because of an error: ${t instanceof Error?t.message:String(t)}`)}}getHttpHeaders(){const t={Accept:"application/json"};return"string"==typeof this.apiKey&&""!==this.apiKey.trim()&&(t.Authorization=this.apiKey),t}}class Gi{blockHeight;path;static fromHex(t){return Gi.fromBinary(Wt(t,"hex"))}static fromReader(t,e=!0){const i=t.readVarIntNum(),r=t.readUInt8(),s=Array(r).fill(null).map(()=>[]);let n,a,o;for(let e=0;e<r;e++){for(o=t.readVarIntNum();o>0;){a=t.readVarIntNum(),n=t.readUInt8();const i={offset:a};1&n?i.duplicate=!0:(2&n&&(i.txid=!0),i.hash=jt(t.read(32).reverse())),Array.isArray(s[e])&&0!==s[e].length||(s[e]=[]),s[e].push(i),o--}s[e].sort((t,e)=>t.offset-e.offset)}return new Gi(i,s,e)}static fromBinary(t){const e=new Ht(t);return Gi.fromReader(e)}static fromCoinbaseTxidAndHeight(t,e){return new Gi(e,[[{offset:0,hash:t,txid:!0}]])}constructor(t,e,i=!0){this.blockHeight=t,this.path=e;const r=Array(this.path.length).fill(0).map(()=>new Set);let s;this.path.forEach((t,e)=>{if(0===t.length&&0===e)throw new Error(`Empty level at height: ${e}`);const s=new Set;t.forEach(t=>{if(s.has(t.offset))throw new Error(`Duplicate offset: ${t.offset}, at height: ${e}`);if(s.add(t.offset),0===e){if(!0!==t.duplicate)for(let e=1;e<this.path.length;e++)r[e].add(t.offset>>e^1)}else if(i&&!r[e].has(t.offset))throw new Error(`Invalid offset: ${t.offset}, at height: ${e}, with legal offsets: ${Array.from(r[e]).join(", ")}`)})}),this.path[0].forEach((t,e)=>{if(0===e&&(s=this.computeRoot(t.hash)),s!==this.computeRoot(t.hash))throw new Error("Mismatched roots")})}toWriter(t){t.writeVarIntNum(this.blockHeight);const e=this.path.length;t.writeUInt8(e);for(let i=0;i<e;i++){const e=Object.keys(this.path[i]).length;t.writeVarIntNum(e);for(const e of this.path[i]){t.writeVarIntNum(e.offset);let i=0;!0===e?.duplicate&&(i|=1),void 0!==e?.txid&&null!==e.txid&&(i|=2),t.writeUInt8(i),1&i||t.write(Wt(e.hash,"hex").reverse())}}}toBinary(){const t=new se;return this.toWriter(t),t.toArray()}toBinaryUint8Array(){const t=new Dt;return this.toWriter(t),t.toUint8Array()}toHex(){return jt(this.toBinaryUint8Array())}indexOf(t){const e=this.path[0].find(e=>e.hash===t);if(null==e)throw new Error(`Transaction ID ${t} not found in the Merkle Path`);return e.offset}computeRoot(t){if("string"!=typeof t){const e=this.path[0].find(t=>Boolean(t?.hash));if(null==e)throw new Error("No valid leaf found in the Merkle Path");t=e.hash}if("string"!=typeof t)throw new Error("Transaction ID is undefined");const e=this.indexOf(t);if("number"!=typeof e)throw new Error(`This proof does not contain the txid: ${t??"undefined"}`);const i=t=>jt(Y(Wt(t,"hex").reverse()).reverse());let r=t;if(1===this.path.length&&1===this.path[0].length)return r;for(let t=0;t<this.path.length;t++){this.path[t];const s=e>>t^1,n=this.findOrComputeLeaf(t,s);if("object"!=typeof n)throw new Error(`Missing hash for index ${e} at height ${t}`);r=!0===n.duplicate?i((r??"")+(r??"")):i(s%2!=0?(n.hash??"")+(r??""):(r??"")+(n.hash??""))}return r}findOrComputeLeaf(t,e){const i=t=>jt(Y(Wt(t,"hex").reverse()).reverse());let r=this.path[t].find(t=>t.offset===e);if(null!=r)return r;if(0===t)return;const s=t-1,n=e<<1,a=this.findOrComputeLeaf(s,n);if(null==a||null==a.hash||""===a.hash)return;const o=this.findOrComputeLeaf(s,n+1);if(null==o)return;let c;return c=!0===o.duplicate?i(a.hash+a.hash):i((o.hash??"")+(a.hash??"")),r={offset:e,hash:c},r}async verify(t,e){const i=this.computeRoot(t);if(0===this.indexOf(t)){const t=await e.currentHeight();if(this.blockHeight+100<t)return!1}return await e.isValidRootForHeight(i,this.blockHeight)}combine(t){if(this.blockHeight!==t.blockHeight)throw new Error("You cannot combine paths which do not have the same block height.");if(this.computeRoot()!==t.computeRoot())throw new Error("You cannot combine paths which do not have the same root.");const e=[];for(let i=0;i<this.path.length;i++){e.push([]);for(let t=0;t<this.path[i].length;t++)e[i].push(this.path[i][t]);for(let r=0;r<t.path[i].length;r++)if(void 0===e[i].find(e=>e.offset===t.path[i][r].offset))e[i].push(t.path[i][r]);else if(void 0!==t.path[i][r]?.txid&&null!==t.path[i][r]?.txid){const s=e[i].find(e=>e.offset===t.path[i][r].offset);null!=s&&(s.txid=!0)}}this.path=e,this.trim()}trim(){const t=(t,e)=>{0!==e.length&&e.slice(-1)[0]===t||e.push(t)},e=(t,e)=>{for(let i=t.length;i>=0;i--){const r=this.path[e].findIndex(e=>e.offset===t[i]);r>=0&&this.path[e].splice(r,1)}},i=e=>{const i=[];for(const r of e)t(r>>1,i);return i};let r=[],s=[];for(let t=0;t<this.path.length;t++)this.path[t].sort((t,e)=>t.offset-e.offset);for(let e=0;e<this.path[0].length;e++){const i=this.path[0][e];if(!0===i.txid)t(i.offset>>1,r);else{const r=i.offset%2==1,n=this.path[0][e+(r?-1:1)];void 0!==n.txid&&null!==n.txid&&n.txid||t(n.offset,s)}}e(s,0);for(let t=1;t<this.path.length;t++)s=r,r=i(r),e(s,t)}}class Xi{_bumpIndex;_tx;_rawTx;_txid;inputTxids=[];isValid=void 0;get bumpIndex(){return this._bumpIndex}set bumpIndex(t){this._bumpIndex=t,this.updateInputTxids()}get hasProof(){return void 0!==this._bumpIndex}get isTxidOnly(){return void 0!==this._txid&&null!==this._txid&&null==this._rawTx&&null==this._tx}get txid(){if(void 0!==this._txid&&null!==this._txid&&""!==this._txid)return this._txid;if(null!=this._tx)return this._txid=this._tx.id("hex"),this._txid;if(null!=this._rawTx)return this._txid=jt(Y(this._rawTx)),this._txid;throw new Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=ir.fromBinary(this._rawTx),this._tx):void 0}get rawTx(){if(null!=this._rawTx)return Array.from(this._rawTx);if(null!=this._tx){const t=this._tx.toUint8Array();return this._rawTx=t,Array.from(t)}}get rawTxUint8Array(){return null!=this._rawTx?this._rawTx:null!=this._tx?(this._rawTx=this._tx.toUint8Array(),this._rawTx):void 0}constructor(t,e){if("string"==typeof t)this._txid=t;else if(t instanceof Uint8Array)this._rawTx=t;else if(Array.isArray(t))this._rawTx=new Uint8Array(t);else{if(!(t instanceof ir))throw new Error("Invalid transaction data type");this._tx=t}this.bumpIndex=e,this.updateInputTxids()}static fromTx(t,e){return new Xi(t,e)}static fromRawTx(t,e){return new Xi(t,e)}static fromTxid(t,e){return new Xi(t,e)}updateInputTxids(){if(this.hasProof||null==this.tx)this.inputTxids=[];else{const t=new Set;for(const e of this.tx.inputs)void 0!==e.sourceTXID&&null!==e.sourceTXID&&""!==e.sourceTXID&&t.add(e.sourceTXID);this.inputTxids=Array.from(t)}}toWriter(t,e){const i=e=>{t.writeUInt8(e)},r=()=>{const e=this.rawTxUint8Array;if(null==e)throw new Error("a valid serialized Transaction is expected");t.write(e)};e===Ji?this.isTxidOnly?(i(Qi.TXID_ONLY),(()=>{if(null==this._txid)throw new Error("Transaction ID (_txid) is undefined");t.writeReverse(Wt(this._txid,"hex"))})()):void 0!==this.bumpIndex?(i(Qi.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex),r()):(i(Qi.RAWTX),r()):(r(),(()=>{void 0===this.bumpIndex?i(Qi.RAWTX):(i(Qi.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex))})())}static fromReader(t,e){let i,r,s;if(e===Ji){const e=t.readUInt8();e===Qi.TXID_ONLY?s=Xi.fromTxid(jt(t.readReverse(32))):(e===Qi.RAWTX_AND_BUMP_INDEX&&(r=t.readVarIntNum()),i=ir.fromReader(t),s=Xi.fromTx(i,r))}else i=ir.fromReader(t),r=0!==t.readUInt8()?t.readVarIntNum():void 0,s=Xi.fromTx(i,r);return s}}const Yi=4022206465,Ji=4022206466,Zi=16843009;var Qi;!function(t){t[t.RAWTX=0]="RAWTX",t[t.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",t[t.TXID_ONLY=2]="TXID_ONLY"}(Qi||(Qi={}));class tr{bumps=[];txs=[];version=Ji;atomicTxid=void 0;txidIndex=void 0;rawBytesCache;hexCache;needsSort=!0;constructor(t=Ji){this.version=t}invalidateSerializationCaches(){this.rawBytesCache=void 0,this.hexCache=void 0}markMutated(t=!0){this.invalidateSerializationCaches(),t&&(this.needsSort=!0)}ensureSerializableState(){for(const t of this.txs)t.txid}ensureSortedForSerialization(){this.needsSort&&this.sortTxs()}getSerializedBytes(){if(this.ensureSerializableState(),null==this.rawBytesCache){this.ensureSortedForSerialization();const t=new Dt;this.toWriter(t),this.rawBytesCache=t.toUint8Array()}return this.rawBytesCache}getBeefForAtomic(t){this.needsSort&&this.sortTxs();const e=this.findTxid(t);if(null==e)throw new Error(`${t} does not exist in this Beef`);const i=this.txs[this.txs.length-1]===e?this:this.clone();if(i!==this){const e=this.txs.findIndex(e=>e.txid===t);i.txs.splice(e+1)}const r=new Dt;return r.writeUInt32LE(Zi),r.writeReverse(Wt(t,"hex")),{beef:i,writer:r}}findTxid(t){return this.ensureTxidIndex().get(t)}ensureTxidIndex(){if(null==this.txidIndex){this.txidIndex=new Map;for(const t of this.txs)this.txidIndex.set(t.txid,t)}return this.txidIndex}deleteFromIndex(t){this.txidIndex?.delete(t)}addToIndex(t){this.txidIndex?.set(t.txid,t)}makeTxidOnly(t){const e=this.txs.findIndex(e=>e.txid===t);if(-1===e)return;let i=this.txs[e];return i.isTxidOnly||(this.deleteFromIndex(t),this.txs.splice(e,1),this.markMutated(!0),i=this.mergeTxidOnly(t)),i}findBump(t){return this.bumps.find(e=>e.path[0].some(e=>e.hash===t))}findTransactionForSigning(t){const e=this.findTxid(t);if(null!=e&&null!=e.tx){for(const t of e.tx.inputs)if(null==t.sourceTransaction){const e=this.findTxid(he(t.sourceTXID,"sourceTXID must be valid"));null!=e&&(t.sourceTransaction=e.tx)}return e.tx}}findAtomicTransaction(t){const e=this.findTxid(t);if(null==e||null==e.tx)return;const i=(t,e)=>{const r=t.findBump(e.id("hex"));if(null!=r)e.merklePath=r;else for(const r of e.inputs){if(null==r.sourceTransaction){const e=t.findTxid(he(r.sourceTXID,"sourceTXID must be valid"));null!=e&&(r.sourceTransaction=e.tx)}if(null!=r.sourceTransaction){const e=t.findBump(r.sourceTransaction.id("hex"));null!=e?r.sourceTransaction.merklePath=e:i(t,r.sourceTransaction)}}};return i(this,e.tx),e.tx}mergeBump(t){let e;this.markMutated(!1);for(let i=0;i<this.bumps.length;i++){const r=this.bumps[i];if(r===t)return i;if(r.blockHeight===t.blockHeight&&r.computeRoot()===t.computeRoot()){r.combine(t),e=i;break}}void 0===e&&(e=this.bumps.length,this.bumps.push(t));const i=this.bumps[e];for(const t of this.txs){const r=t.txid;if(null==t.bumpIndex)for(const s of i.path[0])if(s.hash===r){t.bumpIndex=e,s.txid=!0;break}}return e}mergeRawTx(t,e){this.markMutated(!0);const i=new Xi(t,e);return this.removeExistingTxid(i.txid),this.txs.push(i),this.addToIndex(i),this.tryToValidateBumpIndex(i),i}mergeTransaction(t){this.markMutated(!0);const e=t.id("hex");let i;this.removeExistingTxid(e),null!=t.merklePath&&(i=this.mergeBump(t.merklePath));const r=new Xi(t,i);if(this.txs.push(r),this.addToIndex(r),this.tryToValidateBumpIndex(r),i=r.bumpIndex,void 0===i)for(const e of t.inputs)null!=e.sourceTransaction&&this.mergeTransaction(e.sourceTransaction);return r}removeExistingTxid(t){const e=this.txs.findIndex(e=>e.txid===t);e>=0&&(this.deleteFromIndex(t),this.txs.splice(e,1),this.markMutated(!0))}mergeTxidOnly(t){let e=this.findTxid(t);return null==e&&(e=new Xi(t),this.txs.push(e),this.addToIndex(e),this.tryToValidateBumpIndex(e),this.markMutated(!0)),e}mergeBeefTx(t){let e=this.findTxid(t.txid);if(t.isTxidOnly&&null==e?e=this.mergeTxidOnly(t.txid):null==t._tx||null!=e&&!e.isTxidOnly?null==t._rawTx||null!=e&&!e.isTxidOnly||(e=this.mergeRawTx(t._rawTx)):e=this.mergeTransaction(t._tx),null==e)throw new Error(`Failed to merge BeefTx for txid: ${t.txid}`);return e}mergeBeef(t){const e=t instanceof tr?t:tr.fromBinary(t);for(const t of e.bumps)this.mergeBump(t);for(const t of e.txs)this.mergeBeefTx(t)}isValid(t){return this.verifyValid(t).valid}async verify(t,e){const i=this.verifyValid(e);if(!i.valid)return!1;for(const e of Object.keys(i.roots))if(!await t.isValidRootForHeight(i.roots[e],Number(e)))return!1;return!0}verifyValid(t){const e={valid:!1,roots:{}},i=this.sortTxs();if(i.missingInputs.length>0||i.notValid.length>0||i.txidOnly.length>0&&!0!==t||i.withMissingInputs.length>0)return e;const r={};for(const i of this.txs)if(i.isTxidOnly){if(!0!==t)return e;r[i.txid]=!0}const s=(t,i)=>{const r=t.computeRoot(i);return void 0!==e.roots[t.blockHeight]&&""!==e.roots[t.blockHeight]||(e.roots[t.blockHeight]=r),e.roots[t.blockHeight]===r};for(const t of this.bumps)for(const i of t.path[0])if(!0===i.txid&&"string"==typeof i.hash&&i.hash.length>0&&(r[i.hash]=!0,!s(t,i.hash)))return e;for(const t of this.txs)if(void 0!==t.bumpIndex&&null==this.bumps[t.bumpIndex].path[0].find(e=>e.hash===t.txid))return e;for(const t of this.txs){for(const i of t.inputTxids)if(!r[i])return e;r[t.txid]=!0}return e.valid=!0,e}toWriter(t){t.writeUInt32LE(this.version),t.writeVarIntNum(this.bumps.length);for(const e of this.bumps)t.write(e.toBinary());t.writeVarIntNum(this.txs.length);for(const e of this.txs)e.toWriter(t,this.version)}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}toBinaryAtomic(t){const{beef:e,writer:i}=this.getBeefForAtomic(t);return e.toWriter(i),i.toArray()}toUint8ArrayAtomic(t){const{beef:e,writer:i}=this.getBeefForAtomic(t),r=e.getSerializedBytes(),s=i.toUint8Array(),n=new Uint8Array(s.length+r.length);return n.set(s,0),n.set(r,s.length),n}toHex(){if(null!=this.hexCache)return this.hexCache;const t=this.getSerializedBytes(),e=jt(t);return this.hexCache=e,e}static fromReader(t){let e,i=t.readUInt32LE();if(i===Zi&&(e=jt(t.readReverse(32)),i=t.readUInt32LE()),i!==Yi&&i!==Ji)throw new Error(`Serialized BEEF must start with 4022206465 or ${Ji} but starts with ${i}`);const r=new tr(i),s=t.readVarIntNum();for(let e=0;e<s;e++){const e=Gi.fromReader(t,!1);r.bumps.push(e)}const n=t.readVarIntNum();for(let e=0;e<n;e++){const e=Xi.fromReader(t,i);r.txs.push(e)}return r.atomicTxid=e,r}static fromBinary(t){const e=Ht.makeReader(t);return tr.fromReader(e)}static fromString(t,e="hex"){const i=zt(t,e),r=new Ht(i);return tr.fromReader(r)}tryToValidateBumpIndex(t){if(void 0!==t.bumpIndex)return!0;const e=t.txid;for(let i=0;i<this.bumps.length;i++){const r=this.bumps[i].path[0].findIndex(t=>t.hash===e);if(r>=0)return t.bumpIndex=i,this.bumps[i].path[0][r].txid=!0,!0}return!1}sortTxs(){const t={},e={};let i=[];const r=[],s=[];for(const n of this.txs)e[n.txid]=n,n.isValid=n.hasProof,n.isValid?(t[n.txid]=!0,r.push(n)):n.isTxidOnly&&0===n.inputTxids.length?(t[n.txid]=!0,s.push(n)):i.push(n);const n={},a=[],o=i;i=[];for(const t of o){let r=!1;for(const i of t.inputTxids)void 0===e[i]&&(n[i]=!0,r=!0);r?a.push(t):i.push(t)}for(;i.length>0;){const e=i;i=[];for(const s of e)s.inputTxids.every(e=>t[e])?(t[s.txid]=!0,r.push(s)):i.push(s);if(e.length===i.length)break}const c=i;return this.txs=a.concat(c).concat(s).concat(r),this.needsSort=!1,this.invalidateSerializationCaches(),{missingInputs:Object.keys(n),notValid:c.map(t=>t.txid),valid:Object.keys(t),withMissingInputs:a.map(t=>t.txid),txidOnly:s.map(t=>t.txid)}}clone(){const t=new tr;return t.version=this.version,t.bumps=Array.from(this.bumps),t.txs=Array.from(this.txs),t.txidIndex=void 0,t.needsSort=this.needsSort,t.hexCache=this.hexCache,t.rawBytesCache=this.rawBytesCache,t}trimKnownTxids(t){let e=!1;for(let i=0;i<this.txs.length;){const r=this.txs[i];r.isTxidOnly&&t.includes(r.txid)?(this.deleteFromIndex(r.txid),this.txs.splice(i,1),e=!0):i++}const i=new Set;for(const t of this.txs)void 0!==t.bumpIndex&&i.add(t.bumpIndex);if(i.size<this.bumps.length){const t=new Map;let r=0;for(let e=0;e<this.bumps.length;e++)i.has(e)&&(t.set(e,r),r++);this.bumps=this.bumps.filter((t,e)=>i.has(e));for(const e of this.txs)if(void 0!==e.bumpIndex){const i=t.get(e.bumpIndex);if(void 0===i)throw new Error(`Internal error: bumpIndex ${e.bumpIndex} not found in indexMap`);e.bumpIndex=i}e=!0}e&&this.markMutated(!0)}getValidTxids(){return this.sortTxs().valid}toLogString(){let t="";t+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}\n`;let e=-1;for(const i of this.bumps)e++,t+=` BUMP ${e}\n block: ${i.blockHeight}\n txids: [\n${i.path[0].filter(t=>!0===t.txid).map(t=>` '${t.hash??""}'`).join(",\n")}\n ]\n`;e=-1;for(const i of this.txs)e++,t+=` TX ${e}\n txid: ${i.txid}\n`,void 0!==i.bumpIndex&&(t+=` bumpIndex: ${i.bumpIndex}\n`),i.isTxidOnly?t+=" txidOnly\n":t+=` rawTx length=${i.rawTx?.length??0}\n`,i.inputTxids.length>0&&(t+=` inputs: [\n${i.inputTxids.map(t=>` '${t}'`).join(",\n")}\n ]\n`);return t}addComputedLeaves(){const t=t=>jt(Y(Wt(t,"hex").reverse()).reverse());for(const e of this.bumps)for(let i=1;i<e.path.length;i++)for(const r of e.path[i-1])if("string"==typeof r.hash&&!(1&r.offset)){const s=e.path[i-1].find(t=>t.offset===r.offset+1),n=r.offset>>1;void 0!==s&&"string"==typeof s.hash&&e.path[i].every(t=>t.offset!==n)&&e.path[i].push({offset:n,hash:t(s.hash+r.hash)})}}}const er=tr;class ir{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;rawBytesCache;hexCache;static addPathOrInputs(t,e,i){if("number"==typeof t.pathIndex){const e=i[t.pathIndex];if("object"!=typeof e)throw new Error("Invalid merkle path index found in BEEF!");t.tx.merklePath=e}else for(const r of t.tx.inputs){if(void 0===r.sourceTXID)throw new Error("Input sourceTXID is undefined");const t=e[r.sourceTXID];if("object"!=typeof t)throw new Error(`Reference to unknown TXID in BEEF: ${r.sourceTXID??"undefined"}`);r.sourceTransaction=t.tx,this.addPathOrInputs(t,e,i)}}static fromBEEF(t,e){const{tx:i}=ir.fromAnyBeef(t,e);return i}static fromAtomicBEEF(t){const{tx:e,txid:i,beef:r}=ir.fromAnyBeef(t);if(i!==r.atomicTxid)throw null!=r.atomicTxid?new Error(`Transaction with TXID ${r.atomicTxid} not found in BEEF data.`):new Error("beef must conform to BRC-95 and must contain the subject txid.");return e}static fromAnyBeef(t,e){const i=tr.fromBinary(t);if(i.txs.length<1)throw new Error("beef must include at least one transaction.");const r=e??i.atomicTxid??i.txs.slice(-1)[0].txid,s=i.findAtomicTransaction(r);if(null==s)throw null!=e?new Error(`Transaction with TXID ${r} not found in BEEF data.`):new Error("beef does not contain transaction for atomic txid.");return{tx:s,beef:i,txid:r}}static fromEF(t){const e=Ht.makeReader(t),i=e.readUInt32LE();if("0000000000ef"!==jt(e.read(6)))throw new Error("Invalid EF marker");const r=e.readVarIntNum(),s=[];for(let t=0;t<r;t++){const t=jt(e.readReverse(32)),i=e.readUInt32LE(),r=e.readVarIntNum(),n=e.read(r),a=Ai.fromBinary(n),o=e.readUInt32LE(),c=e.readUInt64LEBn().toNumber(),h=e.readVarIntNum(),u=e.read(h),d=Pi.fromBinary(u),l=new ir(void 0,[],[],void 0);l.outputs=Array(i+1).fill(null),l.outputs[i]={satoshis:c,lockingScript:d},s.push({sourceTransaction:l,sourceTXID:t,sourceOutputIndex:i,unlockingScript:a,sequence:o})}const n=e.readVarIntNum(),a=[];for(let t=0;t<n;t++){const t=e.readUInt64LEBn().toNumber(),i=e.readVarIntNum(),r=e.read(i),s=Pi.fromBinary(r);a.push({satoshis:t,lockingScript:s})}const o=e.readUInt32LE();return new ir(i,s,a,o)}static parseScriptOffsets(t){const e=Ht.makeReader(t),i=[],r=[];e.pos+=4;const s=e.readVarIntNum();for(let t=0;t<s;t++){e.pos+=36;const r=e.readVarIntNum();i.push({vin:t,offset:e.pos,length:r}),e.pos+=r+4}const n=e.readVarIntNum();for(let t=0;t<n;t++){e.pos+=8;const i=e.readVarIntNum();r.push({vout:t,offset:e.pos,length:i}),e.pos+=i}return{inputs:i,outputs:r}}static fromReader(t){const e=t.readUInt32LE(),i=t.readVarIntNum(),r=[];for(let e=0;e<i;e++){const e=jt(t.readReverse(32)),i=t.readUInt32LE(),s=t.readVarIntNum(),n=t.read(s),a=Ai.fromBinary(n),o=t.readUInt32LE();r.push({sourceTXID:e,sourceOutputIndex:i,unlockingScript:a,sequence:o})}const s=t.readVarIntNum(),n=[];for(let e=0;e<s;e++){const e=t.readUInt64LEBn().toNumber(),i=t.readVarIntNum(),r=t.read(i),s=Pi.fromBinary(r);n.push({satoshis:e,lockingScript:s})}const a=t.readUInt32LE();return new ir(e,r,n,a)}static fromBinary(t){const e=t.slice(),i=Uint8Array.from(e),r=new Ht(i),s=ir.fromReader(r);return s.rawBytesCache=i,s}static fromHex(t){const e=zt(t,"hex"),i=new Ht(e),r=ir.fromReader(i);return r.rawBytesCache=e,r.hexCache=jt(e),r}static fromHexEF(t){return ir.fromEF(zt(t,"hex"))}static fromHexBEEF(t,e){return ir.fromBEEF(Wt(t,"hex"),e)}constructor(t=1,e=[],i=[],r=0,s=new Map,n){this.version=t,this.inputs=e,this.outputs=i,this.lockTime=r,this.metadata=s,this.merklePath=n}invalidateSerializationCaches(){this.cachedHash=void 0,this.rawBytesCache=void 0,this.hexCache=void 0}addInput(t){if(void 0===t.sourceTXID&&void 0===t.sourceTransaction)throw new Error("A reference to an an input transaction is required. If the input transaction itself cannot be referenced, its TXID must still be provided.");void 0===t.sequence&&(t.sequence=4294967295),this.invalidateSerializationCaches(),this.inputs.push(t)}addOutput(t){if(this.cachedHash=void 0,!0!==t.change){if(void 0===t.satoshis)throw new Error("either satoshis must be defined or change must be set to true");if(t.satoshis<0)throw new Error("satoshis must be a positive integer or zero")}if(null==t.lockingScript)throw new Error("lockingScript must be defined");this.outputs.push(t)}addP2PKHOutput(t,e){const i=(new Fi).lock(t);if(void 0===e)return this.addOutput({lockingScript:i,change:!0});this.addOutput({lockingScript:i,satoshis:e})}updateMetadata(t){this.metadata={...this.metadata,...t}}async fee(t=qi.getInstance(),e="equal"){if(this.invalidateSerializationCaches(),"number"==typeof t){const e=t;t={computeFee:async()=>e}}const i=await t.computeFee(this),r=this.calculateChange(i);r<=0?this.outputs=this.outputs.filter(t=>!0!==t.change):this.distributeChange(r,e)}calculateChange(t){let e=0;for(const t of this.inputs){if("object"!=typeof t.sourceTransaction)throw new Error("Source transactions are required for all inputs during fee computation");e+=t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0}e-=t;for(const t of this.outputs)!0!==t.change&&void 0!==t.satoshis&&(e-=t.satoshis);return e}distributeChange(t,e){let i=0;const r=this.outputs.filter(t=>t.change);if("random"===e?i=this.distributeRandomChange(t,r):"equal"===e&&(i=this.distributeEqualChange(t,r)),i<t){const e=this.outputs[this.outputs.length-1];void 0!==e.satoshis?e.satoshis+=t-i:e.satoshis=t-i}}distributeRandomChange(t,e){let i=0,r=t;const s=Array(e.length).fill(1);r-=e.length,i+=e.length;for(let t=0;t<e.length-1;t++){const e=this.benfordNumber(0,r);s[t]=s[t]+e,i+=e,r-=e}for(const t of this.outputs)!0===t.change&&(t.satoshis=s.shift());return i}distributeEqualChange(t,e){let i=0;const r=Math.floor(t/e.length);for(const t of e)i+=r,t.satoshis=r;return i}benfordNumber(t,e){const i=Math.floor(9*Math.random())+1;return Math.floor(t+(e-t)*Math.log10(1+1/i)/Math.log10(10))}getFee(){let t=0;for(const e of this.inputs){if("object"!=typeof e.sourceTransaction)throw new Error("Source transactions or sourceSatoshis are required for all inputs to calculate fee");t+=e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0}let e=0;for(const t of this.outputs)e+=t.satoshis??0;return t-e}async sign(){this.invalidateSerializationCaches();for(const t of this.outputs)if(void 0===t.satoshis)throw!0===t.change?new Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing."):new Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");const t=await Promise.all(this.inputs.map(async(t,e)=>"object"==typeof this.inputs[e].unlockingScriptTemplate?await(this.inputs[e]?.unlockingScriptTemplate?.sign(this,e)):await Promise.resolve(void 0)));for(let e=0,i=this.inputs.length;e<i;e++)"object"==typeof this.inputs[e].unlockingScriptTemplate&&(this.inputs[e].unlockingScript=t[e])}async broadcast(t=function(t=!1,e={}){return new zi(t?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",e)}()){return await t.broadcast(this)}writeTransactionBody(t){t.writeUInt32LE(this.version),t.writeVarIntNum(this.inputs.length);for(const e of this.inputs){if(void 0===e.sourceTXID){if(null==e.sourceTransaction)throw new Error("sourceTransaction is undefined");t.write(e.sourceTransaction.hash())}else t.writeReverse(Wt(e.sourceTXID,"hex"));if(t.writeUInt32LE(e.sourceOutputIndex),null==e.unlockingScript)throw new Error("unlockingScript is undefined");const i=e.unlockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i),t.writeUInt32LE(e.sequence??4294967295)}t.writeVarIntNum(this.outputs.length);for(const e of this.outputs){t.writeUInt64LE(e.satoshis??0);const i=e.lockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i)}t.writeUInt32LE(this.lockTime)}buildSerializedBytes(){const t=new Dt;return this.writeTransactionBody(t),t.toUint8Array()}getSerializedBytes(){return null==this.rawBytesCache&&(this.rawBytesCache=this.buildSerializedBytes()),this.rawBytesCache}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}writeEF(t){t.writeUInt32LE(this.version),t.write([0,0,0,0,0,239]),t.writeVarIntNum(this.inputs.length);for(const e of this.inputs){if(void 0===e.sourceTransaction)throw new Error("All inputs must have source transactions when serializing to EF format");if(void 0===e.sourceTXID?t.write(e.sourceTransaction.hash()):t.write(Wt(e.sourceTXID,"hex").reverse()),t.writeUInt32LE(e.sourceOutputIndex),null==e.unlockingScript)throw new Error("unlockingScript is undefined");const i=e.unlockingScript.toBinary();t.writeVarIntNum(i.length),t.write(i),t.writeUInt32LE(e.sequence??4294967295),t.writeUInt64LE(e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0);const r=e.sourceTransaction.outputs[e.sourceOutputIndex].lockingScript.toBinary();t.writeVarIntNum(r.length),t.write(r)}t.writeVarIntNum(this.outputs.length);for(const e of this.outputs){t.writeUInt64LE(e.satoshis??0);const i=e.lockingScript.toBinary();t.writeVarIntNum(i.length),t.write(i)}t.writeUInt32LE(this.lockTime)}toEF(){const t=new se;return this.writeEF(t),t.toArray()}toEFUint8Array(){const t=new Dt;return this.writeEF(t),t.toUint8Array()}toHexEF(){return jt(this.toEFUint8Array())}toHex(){if(null!=this.hexCache)return this.hexCache;const t=this.getSerializedBytes(),e=jt(t);return this.hexCache=e,e}toHexBEEF(){return jt(this.toBEEF())}toHexAtomicBEEF(){return jt(this.toAtomicBEEF())}hash(t){return null==this.cachedHash&&(this.cachedHash=Y(this.getSerializedBytes())),"hex"===t?jt(this.cachedHash):this.cachedHash}id(t){const e=[...this.hash()];return e.reverse(),"hex"===t?jt(e):e}async verify(t=function(){return new Wi}(),e,i){const r=new Set,s=[this];for(;s.length>0;){const n=s.shift(),a=n?.id("hex")??"";if(null!=a&&""!==a&&r.has(a))continue;if("object"==typeof n?.merklePath){if("scripts only"===t){null!=a&&r.add(a);continue}if(await n.merklePath.verify(a,t)){r.add(a);continue}throw new Error(`Invalid merkle path for transaction ${a}`)}if(void 0!==e){if(void 0===n)throw new Error("Transaction is undefined");const t=ir.fromEF(n.toEF());if(delete t.outputs[0].satoshis,t.outputs[0].change=!0,await t.fee(e),n.getFee()<t.getFee())throw new Error(`Verification failed because the transaction ${a} has an insufficient fee and has not been mined.`)}let o=0;if(void 0===n)throw new Error("Transaction is undefined");for(let t=0;t<n.inputs.length;t++){const e=n.inputs[t];if("object"!=typeof e.sourceTransaction)throw new Error(`Verification failed because the input at index ${t} of transaction ${a} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if("object"!=typeof e.unlockingScript)throw new Error(`Verification failed because the input at index ${t} of transaction ${a} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);const c=e.sourceTransaction.outputs[e.sourceOutputIndex];o+=c.satoshis??0;const h=e.sourceTransaction.id("hex");r.has(h)||s.push(e.sourceTransaction);const u=n.inputs.filter((e,i)=>i!==t);if(void 0===e.sourceTXID&&(e.sourceTXID=h),!new Mi({sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:n.version,otherInputs:u,unlockingScript:e.unlockingScript,inputSequence:e.sequence??4294967295,inputIndex:t,outputs:n.outputs,lockTime:n.lockTime,memoryLimit:i}).validate())return!1}let c=0;for(const t of n.outputs){if("number"!=typeof t.satoshis)throw new Error("Every output must have a defined amount during transaction verification.");c+=t.satoshis}if(c>o)return!1;r.add(a)}return!0}writeSerializedBEEF(t,e){t.writeUInt32LE(Yi);const i=[],r=new Map,s=new Map,n=[],a=new Set,o=t=>{const c=t.id("hex");if(a.has(c))return;const h={tx:t},u=t.merklePath,d="object"==typeof u;if(d&&null!=u&&(h.pathIndex=(t=>{const e=r.get(t);if(void 0!==e)return e;const n=`${t.blockHeight}:${t.computeRoot()}`,a=s.get(n);if(void 0!==a)return i[a].combine(t),r.set(t,a),a;const o=i.length;return i.push(t),r.set(t,o),s.set(n,o),o})(u)),!d)for(let i=t.inputs.length-1;i>=0;i--){const r=t.inputs[i];if("object"==typeof r.sourceTransaction)o(r.sourceTransaction);else if(!1===e)throw new Error("A required source transaction is missing!")}a.add(c),n.push(h)};o(this),t.writeVarIntNum(i.length);for(const e of i)t.write(e.toBinary());t.writeVarIntNum(n.length);for(const e of n)t.write(e.tx.toBinary()),"number"==typeof e.pathIndex?(t.writeUInt8(1),t.writeVarIntNum(e.pathIndex)):t.writeUInt8(0);return t.toArray()}toBEEF(t){const e=new se;return this.writeSerializedBEEF(e,t),e.toArray()}toBEEFUint8Array(t){const e=new Dt;return this.writeSerializedBEEF(e,t),e.toArray()}toAtomicBEEF(t){const e=this.hash(),i=this.toBEEF(t);return[1,1,1,1].concat(e,i)}toAtomicBEEFUint8Array(t){const e=new Dt;e.write([1,1,1,1]);const i=this.hash();return e.write(i),this.writeSerializedBEEF(e,t),e.toUint8Array()}async completeWithWallet(t,e,i,r){const s=this.inputs.length,n=this.outputs.length,a={description:e??`Transaction with ${s} input(s) and ${n} output(s)`,inputs:[],outputs:[],lockTime:this.lockTime,version:this.version},o=this.inputs.some(t=>null!=t.unlockingScriptTemplate),c=new tr;for(let t=0;t<this.inputs.length;t++){const e=this.inputs[t];if(null==e.sourceTransaction)throw new Error("All inputs must have a sourceTransaction when using completeWithWallet");const i=e.sourceTransaction.toBEEF();c.mergeBeef(i);const r={outpoint:`${e.sourceTransaction.id("hex")}.${e.sourceOutputIndex}`,inputDescription:"Input from source transaction",sequenceNumber:e.sequence};if(o)if(null!=e.unlockingScriptTemplate){const i=await e.unlockingScriptTemplate.estimateLength(this,t);r.unlockingScriptLength=i}else{if(null==e.unlockingScript)throw new Error(`Input ${t} must have either an unlockingScript or unlockingScriptTemplate`);r.unlockingScript=e.unlockingScript.toHex()}else{if(null==e.unlockingScript)throw new Error("All inputs must have an unlockingScript when using completeWithWallet");r.unlockingScript=e.unlockingScript.toHex()}a.inputs.push(r)}this.inputs.length>0&&(a.inputBEEF=c.toBinary());for(const t of this.outputs)a.outputs.push({satoshis:t.satoshis,lockingScript:t.lockingScript.toHex(),outputDescription:"Output from source transaction"});let h;if(null!=this.metadata?.labels&&Array.isArray(this.metadata.labels)&&(a.labels=this.metadata.labels),o){a.options={...r,signAndProcess:!1};const{signableTransaction:e}=await t.createAction(a,i);if(null==e)throw new Error("Wallet createAction did not return signableTransaction");const s=ir.fromBEEF(e.tx),n={};for(let t=0;t<this.inputs.length;t++){const e=this.inputs[t];if(null!=e.unlockingScriptTemplate){const i=await e.unlockingScriptTemplate.sign(s,t);n[t]={unlockingScript:i.toHex()}}else null!=e.unlockingScript&&(n[t]={unlockingScript:e.unlockingScript.toHex()})}const o=null!=r?{acceptDelayedBroadcast:r.acceptDelayedBroadcast,returnTXIDOnly:r.returnTXIDOnly,noSend:r.noSend,sendWith:r.sendWith}:void 0,c=await t.signAction({reference:e.reference,spends:n,options:o},i);if(null==c.tx)throw new Error("Wallet signAction did not return transaction data");h=c.tx}else{null!=r&&(a.options=r);const{tx:e}=await t.createAction(a,i);if(null==e)throw new Error("Wallet createAction did not return transaction data");h=e}const u=ir.fromAtomicBEEF(h);this.version=u.version,this.inputs=u.inputs,this.outputs=u.outputs,this.lockTime=u.lockTime,this.merklePath=u.merklePath,this.cachedHash=u.cachedHash,this.metadata={...this.metadata,...u.metadata}}}var rr;new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),function(t){t[t.Silent=0]="Silent",t[t.App=1]="App",t[t.Counterparty=2]="Counterparty"}(rr||(rr={}));class sr{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(t,e,i){this.cacheSharedSecret=e,this.retrieveCachedSharedSecret=i,this.anyone=new Je(1).toPublicKey(),this.rootKey="anyone"===t?new Je(1):t,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(t,e,i,r=!1){return i=this.normalizeCounterparty(i),r?this.rootKey.deriveChild(i,this.computeInvoiceNumber(t,e),this.cacheSharedSecret,this.retrieveCachedSharedSecret).toPublicKey():i.deriveChild(this.rootKey,this.computeInvoiceNumber(t,e),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}derivePrivateKey(t,e,i){return i=this.normalizeCounterparty(i),this.rootKey.deriveChild(i,this.computeInvoiceNumber(t,e),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}deriveSymmetricKey(t,e,i){i="anyone"===i?this.anyone:this.normalizeCounterparty(i);const r=this.derivePublicKey(t,e,i),s=this.derivePrivateKey(t,e,i);return new wi(s.deriveSharedSecret(r)?.x?.toArray()??[])}revealCounterpartySecret(t){if("self"===t)throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");t=this.normalizeCounterparty(t);const e=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(e,"test").toHex()===this.rootKey.deriveChild(t,"test").toHex())throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(t).encode(!0)}revealSpecificSecret(t,e,i){t=this.normalizeCounterparty(t);const r=this.rootKey.deriveSharedSecret(t),s=Wt(this.computeInvoiceNumber(e,i),"utf8");return Z(r.encode(!0),s)}normalizeCounterparty(t){if(null==t)throw new Error("counterparty must be self, anyone or a public key!");return"self"===t?this.rootKey.toPublicKey():"anyone"===t?new Je(1).toPublicKey():"string"==typeof t?$e.fromString(t):t}computeInvoiceNumber(t,e){const i=t[0];if(!Number.isInteger(i)||i<0||i>2)throw new Error("Protocol security level must be 0, 1, or 2");const r=t[1].toLowerCase().trim();if(e.length>800)throw new Error("Key IDs must be 800 characters or less");if(e.length<1)throw new Error("Key IDs must be 1 character or more");if(r.length>400){if(!r.startsWith("specific linkage revelation "))throw new Error("Protocol names must be 400 characters or less");if(r.length>430)throw new Error("Specific linkage revelation protocol names must be 430 characters or less")}if(r.length<5)throw new Error("Protocol names must be 5 characters or more");if(r.includes(" "))throw new Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(r))throw new Error("Protocol names can only contain letters, numbers and spaces");if(r.endsWith(" protocol"))throw new Error('No need to end your protocol name with " protocol"');return`${i}-${r}-${e}`}}class nr{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(t,e){this.rootKey="anyone"===t?new Je(1):t,this.keyDeriver=new sr(this.rootKey,(t,e,i)=>{this.cacheSet(`${t.toString()}-${e.toString()}`,i)},(t,e)=>this.cacheGet(`${t.toString()}-${e.toString()}`)),this.identityKey=this.rootKey.toPublicKey().toString(),this.cache=new Map;const i=e?.maxCacheSize;this.maxCacheSize=null!=i&&!isNaN(i)&&i>0?i:1e3}derivePublicKey(t,e,i,r=!1){const s=this.generateCacheKey("derivePublicKey",t,e,i,r);if(this.cache.has(s)){const t=this.cacheGet(s);if(void 0===t)throw new Error("Cached value is undefined");return t}{const n=this.keyDeriver.derivePublicKey(t,e,i,r);return this.cacheSet(s,n),n}}derivePrivateKey(t,e,i){const r=this.generateCacheKey("derivePrivateKey",t,e,i);if(this.cache.has(r)){const t=this.cacheGet(r);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.derivePrivateKey(t,e,i);return this.cacheSet(r,s),s}}deriveSymmetricKey(t,e,i){const r=this.generateCacheKey("deriveSymmetricKey",t,e,i);if(this.cache.has(r)){const t=this.cacheGet(r);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.deriveSymmetricKey(t,e,i);return this.cacheSet(r,s),s}}revealCounterpartySecret(t){const e=this.generateCacheKey("revealCounterpartySecret",t);if(this.cache.has(e)){const t=this.cacheGet(e);if(void 0===t)throw new Error("Cached value is undefined");return t}{const i=this.keyDeriver.revealCounterpartySecret(t);return this.cacheSet(e,i),i}}revealSpecificSecret(t,e,i){const r=this.generateCacheKey("revealSpecificSecret",t,e,i);if(this.cache.has(r)){const t=this.cacheGet(r);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.revealSpecificSecret(t,e,i);return this.cacheSet(r,s),s}}generateCacheKey(t,...e){return`${t}|${e.map(t=>this.serializeArgument(t)).join("|")}`}serializeArgument(t){return t instanceof $e||t instanceof Je?t.toString():Array.isArray(t)?t.map(t=>this.serializeArgument(t)).join(","):"object"==typeof t&&null!==t?JSON.stringify(t):String(t)}cacheGet(t){const e=this.cache.get(t);return this.cache.delete(t),void 0!==e&&this.cache.set(t,e),e}cacheSet(t,e){if(this.cache.size>=this.maxCacheSize){const t=this.cache.keys().next().value;this.cache.delete(t)}this.cache.set(t,e)}}const ar=class{keyDeriver;constructor(t){"string"!=typeof t.identityKey&&(t=new nr(t)),this.keyDeriver=t}async getPublicKey(t){if(t.identityKey){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==t.protocolID||null==t.keyID||""===t.keyID)throw new Error("protocolID and keyID are required if identityKey is false or undefined.");return{publicKey:(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePublicKey(t.protocolID,t.keyID,t.counterparty??"self",t.forSelf).toString()}}async revealCounterpartyKeyLinkage(t){const{publicKey:e}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const i=this.keyDeriver.revealCounterpartySecret(t.counterparty),r=(new _i).generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),$e.fromString(t.counterparty),Te.fromDER(i)),s=[...r.R.encode(!0),...r.SPrime.encode(!0),...r.z.toArray()],n=(new Date).toISOString(),{ciphertext:a}=await this.encrypt({plaintext:i,protocolID:[2,"counterparty linkage revelation"],keyID:n,counterparty:t.verifier}),{ciphertext:o}=await this.encrypt({plaintext:s,protocolID:[2,"counterparty linkage revelation"],keyID:n,counterparty:t.verifier});return{prover:e,verifier:t.verifier,counterparty:t.counterparty,revelationTime:n,encryptedLinkage:a,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(t){const{publicKey:e}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const i=this.keyDeriver.revealSpecificSecret(t.counterparty,t.protocolID,t.keyID),{ciphertext:r}=await this.encrypt({plaintext:i,protocolID:[2,`specific linkage revelation ${t.protocolID[0]} ${t.protocolID[1]}`],keyID:t.keyID,counterparty:t.verifier}),{ciphertext:s}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${t.protocolID[0]} ${t.protocolID[1]}`],keyID:t.keyID,counterparty:t.verifier});return{prover:e,verifier:t.verifier,counterparty:t.counterparty,protocolID:t.protocolID,keyID:t.keyID,encryptedLinkage:r,encryptedLinkageProof:s,proofType:0}}async encrypt(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self").encrypt(t.plaintext)}}async decrypt(t,e){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self").decrypt(t.ciphertext)}}async createHmac(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const e=this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self");return{hmac:Z(e.toArray(),t.data)}}async verifyHmac(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const e=this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self"),i=Z(e.toArray(),t.data),r=t.hmac,s=function(t,e){if(t.length!==e.length)return!1;let i=0;for(let r=0;r<t.length;r++)i|=t[r]^e[r];return 0===i}(Wt(i),Wt(r));if(!s){const t=new Error("HMAC is not valid");throw t.code="ERR_INVALID_HMAC",t}return{valid:s}}async createSignature(t){if(null==t.hashToDirectlySign&&null==t.data)throw new Error("args.data or args.hashToDirectlySign must be valid");const e=t.hashToDirectlySign??X(t.data??[]),i=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePrivateKey(t.protocolID,t.keyID,t.counterparty??"anyone");return{signature:Ve(new a(e),i,!0).toDER()}}async verifySignature(t){if(null==t.hashToDirectlyVerify&&null==t.data)throw new Error("args.data or args.hashToDirectlyVerify must be valid");const e=t.hashToDirectlyVerify??X(t.data??[]),i=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePublicKey(t.protocolID,t.keyID,t.counterparty??"self",t.forSelf),r=Ke(new a(e),Be.fromDER(t.signature),i);if(!r){const t=new Error("Signature is not valid");throw t.code="ERR_INVALID_SIGNATURE",t}return{valid:r}}};class or{CWI;constructor(){if("object"!=typeof window)throw new Error("The window.CWI substrate requires a global window object.");if("object"!=typeof window.CWI)throw new Error("The window.CWI interface does not appear to be bound to the window object.");this.CWI=window.CWI}async createAction(t,e){return await this.CWI.createAction(t,e)}async signAction(t,e){return await this.CWI.signAction(t,e)}async abortAction(t,e){return await this.CWI.abortAction(t,e)}async listActions(t,e){return await this.CWI.listActions(t,e)}async internalizeAction(t,e){return await this.CWI.internalizeAction(t,e)}async listOutputs(t,e){return await this.CWI.listOutputs(t,e)}async relinquishOutput(t,e){return await this.CWI.relinquishOutput(t,e)}async getPublicKey(t,e){return await this.CWI.getPublicKey(t,e)}async revealCounterpartyKeyLinkage(t,e){return await this.CWI.revealCounterpartyKeyLinkage(t,e)}async revealSpecificKeyLinkage(t,e){return await this.CWI.revealSpecificKeyLinkage(t,e)}async encrypt(t,e){return await this.CWI.encrypt(t,e)}async decrypt(t,e){return await this.CWI.decrypt(t,e)}async createHmac(t,e){return await this.CWI.createHmac(t,e)}async verifyHmac(t,e){return await this.CWI.verifyHmac(t,e)}async createSignature(t,e){return await this.CWI.createSignature(t,e)}async verifySignature(t,e){return await this.CWI.verifySignature(t,e)}async acquireCertificate(t,e){return await this.CWI.acquireCertificate(t,e)}async listCertificates(t,e){return await this.CWI.listCertificates(t,e)}async proveCertificate(t,e){return await this.CWI.proveCertificate(t,e)}async relinquishCertificate(t,e){return await this.CWI.relinquishCertificate(t,e)}async discoverByIdentityKey(t,e){return await this.CWI.discoverByIdentityKey(t,e)}async discoverByAttributes(t,e){return await this.CWI.discoverByAttributes(t,e)}async isAuthenticated(t,e){return await this.CWI.isAuthenticated(t,e)}async waitForAuthentication(t,e){return await this.CWI.waitForAuthentication(t,e)}async getHeight(t,e){return await this.CWI.getHeight(t,e)}async getHeaderForHeight(t,e){return await this.CWI.getHeaderForHeight(t,e)}async getNetwork(t,e){return await this.CWI.getNetwork(t,e)}async getVersion(t,e){return await this.CWI.getVersion(t,e)}}class cr extends Error{code;isError=!0;constructor(t,e=1,i){super(t),this.code=e,this.name=this.constructor.name,null!=i&&""!==i?this.stack=i:Error.captureStackTrace(this,this.constructor)}static unknownToJson(t){let e;return!0===t.isError&&String(t.name).startsWith("WERR_")?(e={name:t.name,message:t.message,isError:!0},"WERR_REVIEW_ACTIONS"===e.name?(e.reviewActionResults=t.reviewActionResults,e.sendWithResults=t.sendWithResults,e.txid=t.txid,e.tx=t.tx,e.noSendChange=t.noSendChange,e.code=5):"WERR_INVALID_PARAMETER"===e.name?(e.parameter=t.parameter,e.code=6):"WERR_INSUFFICIENT_FUNDS"===e.name&&(e.totalSatoshisNeeded=t.totalSatoshisNeeded,e.moreSatoshisNeeded=t.moreSatoshisNeeded,e.code=7)):e=t instanceof Error?{name:t.constructor.name,message:t.message,isError:!0}:{name:"WERR_UNKNOWN",message:String(t),isError:!0},JSON.stringify(e)}}var hr,ur;!function(t){t[t.unknownError=1]="unknownError",t[t.unsupportedAction=2]="unsupportedAction",t[t.invalidHmac=3]="invalidHmac",t[t.invalidSignature=4]="invalidSignature",t[t.reviewActions=5]="reviewActions",t[t.invalidParameter=6]="invalidParameter",t[t.insufficientFunds=7]="insufficientFunds"}(hr||(hr={}));class dr{domain;constructor(t="*"){if("object"!=typeof window)throw new Error("The XDM substrate requires a global window object.");if("function"!=typeof window.postMessage)throw new Error("The window object does not seem to support postMessage calls.");this.domain=t}async invoke(t,e){return await new Promise((i,r)=>{const s=Zt(We(12)),n=t=>{if("CWI"===t.data.type&&t.isTrusted&&t.data.id===s&&!0!==t.data.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",n),"error"===t.data.status){const e=new cr(t.data.description,t.data.code);r(e)}else i(t.data.result)};window.addEventListener("message",n),window.parent.postMessage({type:"CWI",isInvocation:!0,id:s,call:t,args:e},this.domain)})}async createAction(t){return await this.invoke("createAction",t)}async signAction(t){return await this.invoke("signAction",t)}async abortAction(t){return await this.invoke("abortAction",t)}async listActions(t){return await this.invoke("listActions",t)}async internalizeAction(t){return await this.invoke("internalizeAction",t)}async listOutputs(t){return await this.invoke("listOutputs",t)}async relinquishOutput(t){return await this.invoke("relinquishOutput",t)}async getPublicKey(t){return await this.invoke("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.invoke("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.invoke("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.invoke("encrypt",t)}async decrypt(t){return await this.invoke("decrypt",t)}async createHmac(t){return await this.invoke("createHmac",t)}async verifyHmac(t){return await this.invoke("verifyHmac",t)}async createSignature(t){return await this.invoke("createSignature",t)}async verifySignature(t){return await this.invoke("verifySignature",t)}async acquireCertificate(t){return await this.invoke("acquireCertificate",t)}async listCertificates(t){return await this.invoke("listCertificates",t)}async proveCertificate(t){return await this.invoke("proveCertificate",t)}async relinquishCertificate(t){return await this.invoke("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.invoke("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.invoke("discoverByAttributes",t)}async isAuthenticated(t){return await this.invoke("isAuthenticated",t)}async waitForAuthentication(t){return await this.invoke("waitForAuthentication",t)}async getHeight(t){return await this.invoke("getHeight",t)}async getHeaderForHeight(t){return await this.invoke("getHeaderForHeight",t)}async getNetwork(t){return await this.invoke("getNetwork",t)}async getVersion(t){return await this.invoke("getVersion",t)}}class lr{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(t,e,i,r,s,n,a){this.type=t,this.serialNumber=e,this.subject=i,this.certifier=r,this.revocationOutpoint=s,this.fields=n,this.signature=a}toBinary(t=!0){const e=new se,i=Wt(this.type,"base64");e.write(i);const r=Wt(this.serialNumber,"base64");e.write(r);const s=Wt(this.subject,"hex");e.write(s);const n=Wt(this.certifier,"hex");e.write(n);const[a,o]=this.revocationOutpoint.split("."),c=Wt(a,"hex");e.write(c),e.writeVarIntNum(Number(o));const h=Object.keys(this.fields).sort();e.writeVarIntNum(h.length);for(const t of h){const i=this.fields[t],r=Wt(t,"utf8");e.writeVarIntNum(r.length),e.write(r);const s=Wt(i,"utf8");e.writeVarIntNum(s.length),e.write(s)}if(t&&(this.signature??"").length>0){const t=Wt(this.signature,"hex");e.write(t)}return e.toArray()}static fromBinary(t){const e=new ne(t),i=Zt(e.read(32)),r=Zt(e.read(32)),s=e.read(33),n=jt(s),a=e.read(33),o=jt(a),c=e.read(32),h=`${jt(c)}.${e.readVarIntNum()}`,u=e.readVarIntNum(),d={};for(let t=0;t<u;t++){const t=e.readVarIntNum(),i=e.read(t),r=Yt(i),s=e.readVarIntNum(),n=e.read(s),a=Yt(n);d[r]=a}let l;if(!e.eof()){const t=e.read();l=Be.fromDER(t).toString("hex")}return new lr(i,r,n,o,h,d,l)}async verify(){const t=new ar("anyone"),e=this.toBinary(!1),i=this.signature??"",{valid:r}=await t.verifySignature({signature:Wt(i,"hex"),data:e,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return r}async sign(t){if(null!=this.signature&&this.signature.length>0)throw new Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await t.getPublicKey({identityKey:!0})).publicKey;const e=this.toBinary(!1),{signature:i}=await t.createSignature({data:e,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=jt(i)}static getCertificateFieldEncryptionDetails(t,e){return{protocolID:[2,"certificate field encryption"],keyID:e?`${e} ${t}`:t}}static fromObject(t){return new lr(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,t.signature)}}!function(t){t[t.createAction=1]="createAction",t[t.signAction=2]="signAction",t[t.abortAction=3]="abortAction",t[t.listActions=4]="listActions",t[t.internalizeAction=5]="internalizeAction",t[t.listOutputs=6]="listOutputs",t[t.relinquishOutput=7]="relinquishOutput",t[t.getPublicKey=8]="getPublicKey",t[t.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",t[t.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",t[t.encrypt=11]="encrypt",t[t.decrypt=12]="decrypt",t[t.createHmac=13]="createHmac",t[t.verifyHmac=14]="verifyHmac",t[t.createSignature=15]="createSignature",t[t.verifySignature=16]="verifySignature",t[t.acquireCertificate=17]="acquireCertificate",t[t.listCertificates=18]="listCertificates",t[t.proveCertificate=19]="proveCertificate",t[t.relinquishCertificate=20]="relinquishCertificate",t[t.discoverByIdentityKey=21]="discoverByIdentityKey",t[t.discoverByAttributes=22]="discoverByAttributes",t[t.isAuthenticated=23]="isAuthenticated",t[t.waitForAuthentication=24]="waitForAuthentication",t[t.getHeight=25]="getHeight",t[t.getHeaderForHeight=26]="getHeaderForHeight",t[t.getNetwork=27]="getNetwork",t[t.getVersion=28]="getVersion"}(ur||(ur={}));const fr=ur;class pr{wire;constructor(t){this.wire=t}async transmit(t,e="",i=[]){const r=new se;r.writeUInt8(fr[t]);const s=Wt(e,"utf8");r.writeUInt8(s.length),r.write(s),i.length>0&&r.write(i);const n=r.toArray(),a=await this.wire.transmitToWallet(n),o=new ne(a),c=o.readUInt8();if(0===c)return o.read();{const t=o.readVarIntNum(),e=o.read(t),i=Yt(e),r=o.readVarIntNum(),s=o.read(r),n=Yt(s);throw new cr(i,c,n)}}async createAction(t,e){const i=new se,r=Wt(t.description,"utf8");if(i.writeVarIntNum(r.length),i.write(r),null!=t.inputBEEF?(i.writeVarIntNum(t.inputBEEF.length),i.write(t.inputBEEF)):i.writeVarIntNum(-1),null!=t.inputs){i.writeVarIntNum(t.inputs.length);for(const e of t.inputs){if(i.write(this.encodeOutpoint(e.outpoint)),null!=e.unlockingScript&&""!==e.unlockingScript){const t=Wt(e.unlockingScript,"hex");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1),i.writeVarIntNum(e.unlockingScriptLength??0);const t=Wt(e.inputDescription,"utf8");i.writeVarIntNum(t.length),i.write(t),"number"==typeof e.sequenceNumber?i.writeVarIntNum(e.sequenceNumber):i.writeVarIntNum(-1)}}else i.writeVarIntNum(-1);if(null!=t.outputs){i.writeVarIntNum(t.outputs.length);for(const e of t.outputs){const t=Wt(e.lockingScript,"hex");i.writeVarIntNum(t.length),i.write(t),i.writeVarIntNum(e.satoshis);const r=Wt(e.outputDescription,"utf8");if(i.writeVarIntNum(r.length),i.write(r),null!=e.basket&&""!==e.basket){const t=Wt(e.basket,"utf8");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1);if(null!=e.customInstructions&&""!==e.customInstructions){const t=Wt(e.customInstructions,"utf8");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1);if(null!=e.tags){i.writeVarIntNum(e.tags.length);for(const t of e.tags){const e=Wt(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}}else i.writeVarIntNum(-1)}}else i.writeVarIntNum(-1);if("number"==typeof t.lockTime?i.writeVarIntNum(t.lockTime):i.writeVarIntNum(-1),"number"==typeof t.version?i.writeVarIntNum(t.version):i.writeVarIntNum(-1),null!=t.labels){i.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Wt(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}}else i.writeVarIntNum(-1);if(null!=t.options){if(i.writeInt8(1),"boolean"==typeof t.options.signAndProcess?i.writeInt8(t.options.signAndProcess?1:0):i.writeInt8(-1),"boolean"==typeof t.options.acceptDelayedBroadcast?i.writeInt8(t.options.acceptDelayedBroadcast?1:0):i.writeInt8(-1),"known"===t.options.trustSelf?i.writeInt8(1):i.writeInt8(-1),null!=t.options.knownTxids){i.writeVarIntNum(t.options.knownTxids.length);for(const e of t.options.knownTxids){const t=Wt(e,"hex");i.write(t)}}else i.writeVarIntNum(-1);if("boolean"==typeof t.options.returnTXIDOnly?i.writeInt8(t.options.returnTXIDOnly?1:0):i.writeInt8(-1),"boolean"==typeof t.options.noSend?i.writeInt8(t.options.noSend?1:0):i.writeInt8(-1),null!=t.options.noSendChange){i.writeVarIntNum(t.options.noSendChange.length);for(const e of t.options.noSendChange)i.write(this.encodeOutpoint(e))}else i.writeVarIntNum(-1);if(null!=t.options.sendWith){i.writeVarIntNum(t.options.sendWith.length);for(const e of t.options.sendWith){const t=Wt(e,"hex");i.write(t)}}else i.writeVarIntNum(-1);"boolean"==typeof t.options.randomizeOutputs?i.writeInt8(t.options.randomizeOutputs?1:0):i.writeInt8(-1)}else i.writeInt8(0);const s=await this.transmit("createAction",e,i.toArray()),n=new ne(s),a={};if(1===n.readInt8()){const t=n.read(32);a.txid=jt(t)}if(1===n.readInt8()){const t=n.readVarIntNum();a.tx=n.read(t)}const o=n.readVarIntNum();if(o>=0){a.noSendChange=[];for(let t=0;t<o;t++){const t=this.readOutpoint(n);a.noSendChange.push(t)}}const c=n.readVarIntNum();if(c>=0){a.sendWithResults=[];for(let t=0;t<c;t++){const t=n.read(32),e=jt(t),i=n.readInt8();let r="unproven";1===i?r="unproven":2===i?r="sending":3===i&&(r="failed"),a.sendWithResults.push({txid:e,status:r})}}if(1===n.readInt8()){const t=n.readVarIntNum(),e=n.read(t),i=n.readVarIntNum(),r=n.read(i);a.signableTransaction={tx:e,reference:Zt(r)}}return a}async signAction(t,e){const i=new se,r=Object.keys(t.spends);i.writeVarIntNum(r.length);for(const e of r){i.writeVarIntNum(Number(e));const r=t.spends[Number(e)],s=Wt(r.unlockingScript,"hex");i.writeVarIntNum(s.length),i.write(s),"number"==typeof r.sequenceNumber?i.writeVarIntNum(r.sequenceNumber):i.writeVarIntNum(-1)}const s=Wt(t.reference,"base64");if(i.writeVarIntNum(s.length),i.write(s),null!=t.options)if(i.writeInt8(1),"boolean"==typeof t.options.acceptDelayedBroadcast?i.writeInt8(t.options.acceptDelayedBroadcast?1:0):i.writeInt8(-1),"boolean"==typeof t.options.returnTXIDOnly?i.writeInt8(t.options.returnTXIDOnly?1:0):i.writeInt8(-1),"boolean"==typeof t.options.noSend?i.writeInt8(t.options.noSend?1:0):i.writeInt8(-1),null!=t.options.sendWith){i.writeVarIntNum(t.options.sendWith.length);for(const e of t.options.sendWith){const t=Wt(e,"hex");i.write(t)}}else i.writeVarIntNum(-1);else i.writeInt8(0);const n=await this.transmit("signAction",e,i.toArray()),a=new ne(n),o={};if(1===a.readInt8()){const t=a.read(32);o.txid=jt(t)}if(1===a.readInt8()){const t=a.readVarIntNum();o.tx=a.read(t)}const c=a.readVarIntNum();if(c>=0){o.sendWithResults=[];for(let t=0;t<c;t++){const t=a.read(32),e=jt(t),i=a.readInt8();let r="unproven";1===i?r="unproven":2===i?r="sending":3===i&&(r="failed"),o.sendWithResults.push({txid:e,status:r})}}return o}async abortAction(t,e){return await this.transmit("abortAction",e,Wt(t.reference,"base64")),{aborted:!0}}async listActions(t,e){const i=new se;i.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Wt(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}"any"===t.labelQueryMode?i.writeInt8(1):"all"===t.labelQueryMode?i.writeInt8(2):i.writeInt8(-1);const r=[t.includeLabels,t.includeInputs,t.includeInputSourceLockingScripts,t.includeInputUnlockingScripts,t.includeOutputs,t.includeOutputLockingScripts];for(const t of r)"boolean"==typeof t?i.writeInt8(t?1:0):i.writeInt8(-1);"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const s=await this.transmit("listActions",e,i.toArray()),n=new ne(s),a=n.readVarIntNum(),o=[];for(let t=0;t<a;t++){const t=n.read(32),e=jt(t),i=n.readVarIntNum(),r=n.readInt8();let s;switch(r){case 1:s="completed";break;case 2:s="unprocessed";break;case 3:s="sending";break;case 4:s="unproven";break;case 5:s="unsigned";break;case 6:s="nosend";break;case 7:s="nonfinal";break;case 8:s="failed";break;default:throw new Error(`Unknown status code: ${r}`)}const a=1===n.readInt8(),c=n.readVarIntNum(),h=n.read(c),u={txid:e,satoshis:i,status:s,isOutgoing:a,description:Yt(h),version:0,lockTime:0},d=n.readVarIntNum();if(d>=0){u.labels=[];for(let t=0;t<d;t++){const t=n.readVarIntNum(),e=n.read(t);u.labels.push(Yt(e))}}u.version=n.readVarIntNum(),u.lockTime=n.readVarIntNum();const l=n.readVarIntNum();if(l>=0){u.inputs=[];for(let t=0;t<l;t++){const t=this.readOutpoint(n),e=n.readVarIntNum(),i=n.readVarIntNum();let r;if(i>=0){const t=n.read(i);r=jt(t)}const s=n.readVarIntNum();let a;if(s>=0){const t=n.read(s);a=jt(t)}const o=n.readVarIntNum(),c=n.read(o),h=Yt(c),d=n.readVarIntNum();u.inputs.push({sourceOutpoint:t,sourceSatoshis:e,sourceLockingScript:r,unlockingScript:a,inputDescription:h,sequenceNumber:d})}}const f=n.readVarIntNum();if(f>=0){u.outputs=[];for(let t=0;t<f;t++){const t=n.readVarIntNum(),e=n.readVarIntNum(),i=n.readVarIntNum();let r;if(i>=0){const t=n.read(i);r=jt(t)}const s=1===n.readInt8(),a=n.readVarIntNum(),o=n.read(a),c=Yt(o),h=n.readVarIntNum();let d;if(h>=0){const t=n.read(h);d=Yt(t)}const l=n.readVarIntNum(),f=[];if(l>=0)for(let t=0;t<l;t++){const t=n.readVarIntNum(),e=n.read(t);f.push(Yt(e))}const p=n.readVarIntNum();let g;if(p>=0){const t=n.read(p);g=Yt(t)}u.outputs.push({outputIndex:t,satoshis:e,lockingScript:r,spendable:s,outputDescription:c,basket:d,tags:f,customInstructions:g})}}o.push(u)}return{totalActions:a,actions:o}}async internalizeAction(t,e){const i=new se;i.writeVarIntNum(t.tx.length),i.write(t.tx),i.writeVarIntNum(t.outputs.length);for(const e of t.outputs)if(i.writeVarIntNum(e.outputIndex),"wallet payment"===e.protocol){if(null==e.paymentRemittance)throw new Error("Payment remittance is required for wallet payment");i.writeUInt8(1),i.write(Wt(e.paymentRemittance.senderIdentityKey,"hex"));const t=Wt(e.paymentRemittance.derivationPrefix,"base64");i.writeVarIntNum(t.length),i.write(t);const r=Wt(e.paymentRemittance.derivationSuffix,"base64");i.writeVarIntNum(r.length),i.write(r)}else{i.writeUInt8(2);const t=Wt(e.insertionRemittance?.basket,"utf8");if(i.writeVarIntNum(t.length),i.write(t),"string"==typeof e.insertionRemittance?.customInstructions&&""!==e.insertionRemittance.customInstructions){const t=Wt(e.insertionRemittance.customInstructions,"utf8");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1);if("object"==typeof e.insertionRemittance?.tags){i.writeVarIntNum(e.insertionRemittance.tags.length);for(const t of e.insertionRemittance.tags){const e=Wt(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}}else i.writeVarIntNum(0)}if("object"==typeof t.labels){i.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Wt(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}}else i.writeVarIntNum(-1);const r=Wt(t.description);return i.writeVarIntNum(r.length),i.write(r),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),await this.transmit("internalizeAction",e,i.toArray()),{accepted:!0}}async listOutputs(t,e){const i=new se,r=Wt(t.basket,"utf8");if(i.writeVarIntNum(r.length),i.write(r),"object"==typeof t.tags){i.writeVarIntNum(t.tags.length);for(const e of t.tags){const t=Wt(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}}else i.writeVarIntNum(0);"all"===t.tagQueryMode?i.writeInt8(1):"any"===t.tagQueryMode?i.writeInt8(2):i.writeInt8(-1),"locking scripts"===t.include?i.writeInt8(1):"entire transactions"===t.include?i.writeInt8(2):i.writeInt8(-1),"boolean"==typeof t.includeCustomInstructions?i.writeInt8(t.includeCustomInstructions?1:0):i.writeInt8(-1),"boolean"==typeof t.includeTags?i.writeInt8(t.includeTags?1:0):i.writeInt8(-1),"boolean"==typeof t.includeLabels?i.writeInt8(t.includeLabels?1:0):i.writeInt8(-1),"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const s=await this.transmit("listOutputs",e,i.toArray()),n=new ne(s),a=n.readVarIntNum(),o=n.readVarIntNum();let c;o>=0&&(c=n.read(o));const h=[];for(let t=0;t<a;t++){const t={spendable:!0,outpoint:this.readOutpoint(n),satoshis:n.readVarIntNum()},e=n.readVarIntNum();e>=0&&(t.lockingScript=jt(n.read(e)));const i=n.readVarIntNum();i>=0&&(t.customInstructions=Yt(n.read(i)));const r=n.readVarIntNum();if(-1!==r){const e=[];for(let t=0;t<r;t++){const t=n.readVarIntNum();e.push(Yt(n.read(t)))}t.tags=e}const s=n.readVarIntNum();if(-1!==s){const e=[];for(let t=0;t<s;t++){const t=n.readVarIntNum();e.push(Yt(n.read(t)))}t.labels=e}h.push(t)}return{totalOutputs:a,BEEF:c,outputs:h}}async relinquishOutput(t,e){const i=new se,r=Wt(t.basket,"utf8");return i.writeVarIntNum(r.length),i.write(r),i.write(this.encodeOutpoint(t.output)),await this.transmit("relinquishOutput",e,i.toArray()),{relinquished:!0}}encodeOutpoint(t){const e=new se,[i,r]=t.split(".");return e.write(Wt(i,"hex")),e.writeVarIntNum(Number(r)),e.toArray()}readOutpoint(t){return`${jt(t.read(32))}.${t.readVarIntNum()}`}async getPublicKey(t,e){const i=new se;i.writeUInt8(t.identityKey?1:0),t.identityKey?i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)):(i.write(this.encodeKeyRelatedParams(t.protocolID??=[rr.Silent,"default"],t.keyID??="",t.counterparty,t.privileged,t.privilegedReason)),"boolean"==typeof t.forSelf?i.writeInt8(t.forSelf?1:0):i.writeInt8(-1)),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const r=await this.transmit("getPublicKey",e,i.toArray());return{publicKey:jt(r)}}async revealCounterpartyKeyLinkage(t,e){const i=new se;i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),i.write(Wt(t.counterparty,"hex")),i.write(Wt(t.verifier,"hex"));const r=await this.transmit("revealCounterpartyKeyLinkage",e,i.toArray()),s=new ne(r),n=jt(s.read(33)),a=jt(s.read(33)),o=jt(s.read(33)),c=s.readVarIntNum(),h=Yt(s.read(c)),u=s.readVarIntNum(),d=s.read(u),l=s.readVarIntNum();return{prover:n,verifier:a,counterparty:o,revelationTime:h,encryptedLinkage:d,encryptedLinkageProof:s.read(l)}}async revealSpecificKeyLinkage(t,e){const i=new se;i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.write(Wt(t.verifier,"hex"));const r=await this.transmit("revealSpecificKeyLinkage",e,i.toArray()),s=new ne(r),n=jt(s.read(33)),a=jt(s.read(33)),o=jt(s.read(33)),c=s.readUInt8(),h=s.readVarIntNum(),u=Yt(s.read(h)),d=s.readVarIntNum(),l=Yt(s.read(d)),f=s.readVarIntNum(),p=s.read(f),g=s.readVarIntNum();return{prover:n,verifier:a,counterparty:o,protocolID:[c,u],keyID:l,encryptedLinkage:p,encryptedLinkageProof:s.read(g),proofType:s.readUInt8()}}async encrypt(t,e){const i=new se;return i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.plaintext.length),i.write(t.plaintext),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{ciphertext:await this.transmit("encrypt",e,i.toArray())}}async decrypt(t,e){const i=new se;return i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.ciphertext.length),i.write(t.ciphertext),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{plaintext:await this.transmit("decrypt",e,i.toArray())}}async createHmac(t,e){const i=new se;return i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.data.length),i.write(t.data),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{hmac:await this.transmit("createHmac",e,i.toArray())}}async verifyHmac(t,e){const i=new se;return i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.write(t.hmac),i.writeVarIntNum(t.data.length),i.write(t.data),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),await this.transmit("verifyHmac",e,i.toArray()),{valid:!0}}async createSignature(t,e){const i=new se;return i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),"object"==typeof t.data?(i.writeUInt8(1),i.writeVarIntNum(t.data.length),i.write(t.data)):(i.writeUInt8(2),i.write(t.hashToDirectlySign??=[])),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{signature:await this.transmit("createSignature",e,i.toArray())}}async verifySignature(t,e){const i=new se;return i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),"boolean"==typeof t.forSelf?i.writeInt8(t.forSelf?1:0):i.writeInt8(-1),i.writeVarIntNum(t.signature.length),i.write(t.signature),"object"==typeof t.data?(i.writeUInt8(1),i.writeVarIntNum(t.data.length),i.write(t.data)):(i.writeUInt8(2),i.write(t.hashToDirectlyVerify??[])),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),await this.transmit("verifySignature",e,i.toArray()),{valid:!0}}encodeKeyRelatedParams(t,e,i,r,s){const n=new se;n.writeUInt8(t[0]);const a=Wt(t[1],"utf8");n.writeVarIntNum(a.length),n.write(a);const o=Wt(e,"utf8");return n.writeVarIntNum(o.length),n.write(o),"string"!=typeof i?n.writeUInt8(0):"self"===i?n.writeUInt8(11):"anyone"===i?n.writeUInt8(12):n.write(Wt(i,"hex")),n.write(this.encodePrivilegedParams(r,s)),n.toArray()}async acquireCertificate(t,e){const i=new se;i.write(Wt(t.type,"base64")),i.write(Wt(t.certifier,"hex"));const r=Object.entries(t.fields);i.writeVarIntNum(r.length);for(const[t,e]of r){const r=Wt(t,"utf8"),s=Wt(e,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(s.length),i.write(s)}if(i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),i.writeUInt8("direct"===t.acquisitionProtocol?1:2),"direct"===t.acquisitionProtocol){i.write(Wt(t.serialNumber,"base64")),i.write(this.encodeOutpoint(t.revocationOutpoint??""));const e=Wt(t.signature,"hex");i.writeVarIntNum(e.length),i.write(e);const r="certifier"!==t.keyringRevealer?Wt(t.keyringRevealer,"hex"):[11];i.write(r);const s=Object.keys(t.keyringForSubject??{});i.writeVarIntNum(s.length);for(let e=0;e<s.length;e++){const r=Wt(s[e],"utf8");i.writeVarIntNum(r.length),i.write(r);const n=Wt(t.keyringForSubject?.[s[e]],"base64");i.writeVarIntNum(n.length),i.write(n)}}else{const e=Wt(t.certifierUrl,"utf8");i.writeVarIntNum(e.length),i.write(e)}const s=await this.transmit("acquireCertificate",e,i.toArray()),n=lr.fromBinary(s);return{...n,signature:n.signature}}encodePrivilegedParams(t,e){const i=new se;if("boolean"==typeof t?i.writeInt8(t?1:0):i.writeInt8(-1),"string"==typeof e){const t=Wt(e,"utf8");i.writeInt8(t.length),i.write(t)}else i.writeInt8(-1);return i.toArray()}async listCertificates(t,e){const i=new se;i.writeVarIntNum(t.certifiers.length);for(let e=0;e<t.certifiers.length;e++)i.write(Wt(t.certifiers[e],"hex"));i.writeVarIntNum(t.types.length);for(let e=0;e<t.types.length;e++)i.write(Wt(t.types[e],"base64"));"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason));const r=await this.transmit("listCertificates",e,i.toArray()),s=new ne(r),n=s.readVarIntNum(),a=[];for(let t=0;t<n;t++){const t=s.readVarIntNum(),e=s.read(t),i=lr.fromBinary(e),r={};if(1===s.readInt8()){const t=s.readVarIntNum();for(let e=0;e<t;e++){const t=s.readVarIntNum(),e=Yt(s.read(t)),i=s.readVarIntNum();r[e]=Zt(s.read(i))}}const n=s.readVarIntNum();let o;n>0&&(o=Yt(s.read(n))),a.push({...i,signature:i.signature,keyring:r,verifier:o})}return{totalCertificates:n,certificates:a}}async proveCertificate(t,e){const i=new se,r=Wt(t.certificate.type,"base64");i.write(r);const s=Wt(t.certificate.subject,"hex");i.write(s);const n=Wt(t.certificate.serialNumber,"base64");i.write(n);const a=Wt(t.certificate.certifier,"hex");i.write(a);const o=this.encodeOutpoint(t.certificate.revocationOutpoint??"");i.write(o);const c=Wt(t.certificate.signature,"hex");i.writeVarIntNum(c.length),i.write(c);const h=Object.entries(t.certificate.fields??{});i.writeVarIntNum(h.length);for(const[t,e]of h){const r=Wt(t,"utf8"),s=Wt(e,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(s.length),i.write(s)}i.writeVarIntNum(t.fieldsToReveal.length);for(const e of t.fieldsToReveal){const t=Wt(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}i.write(Wt(t.verifier,"hex")),i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason));const u=await this.transmit("proveCertificate",e,i.toArray()),d=new ne(u),l=d.readVarIntNum(),f={};for(let t=0;t<l;t++){const t=d.readVarIntNum(),e=Yt(d.read(t)),i=d.readVarIntNum();f[e]=Zt(d.read(i))}return{keyringForVerifier:f}}async relinquishCertificate(t,e){const i=new se,r=Wt(t.type,"base64");i.write(r);const s=Wt(t.serialNumber,"base64");i.write(s);const n=Wt(t.certifier,"hex");return i.write(n),await this.transmit("relinquishCertificate",e,i.toArray()),{relinquished:!0}}parseDiscoveryResult(t){const e=new ne(t),i=e.readVarIntNum(),r=[];for(let t=0;t<i;t++){const t=e.readVarIntNum(),i=e.read(t),s=lr.fromBinary(i),n=e.readVarIntNum(),a=Yt(e.read(n)),o=e.readVarIntNum(),c=Yt(e.read(o)),h=e.readVarIntNum(),u=Yt(e.read(h)),d=e.readUInt8(),l={},f=e.readVarIntNum();for(let t=0;t<f;t++){const t=e.readVarIntNum(),i=Yt(e.read(t)),r=e.readVarIntNum();l[i]=e.read(r)}const p={},g=e.readVarIntNum();for(let t=0;t<g;t++){const t=e.readVarIntNum(),i=Yt(e.read(t)),r=e.readVarIntNum();p[i]=Yt(e.read(r))}r.push({...s,signature:s.signature,certifierInfo:{iconUrl:c,name:a,description:u,trust:d},publiclyRevealedKeyring:l,decryptedFields:p})}return{totalCertificates:i,certificates:r}}async discoverByIdentityKey(t,e){const i=new se;i.write(Wt(t.identityKey,"hex")),"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const r=await this.transmit("discoverByIdentityKey",e,i.toArray());return this.parseDiscoveryResult(r)}async discoverByAttributes(t,e){const i=new se,r=Object.keys(t.attributes);i.writeVarIntNum(r.length);for(let e=0;e<r.length;e++)i.writeVarIntNum(r[e].length),i.write(Wt(r[e],"utf8")),i.writeVarIntNum(t.attributes[r[e]].length),i.write(Wt(t.attributes[r[e]],"utf8"));"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const s=await this.transmit("discoverByAttributes",e,i.toArray());return this.parseDiscoveryResult(s)}async isAuthenticated(t,e){return{authenticated:1===(await this.transmit("isAuthenticated",e))[0]}}async waitForAuthentication(t,e){return await this.transmit("waitForAuthentication",e),{authenticated:!0}}async getHeight(t,e){const i=await this.transmit("getHeight",e);return{height:new ne(i).readVarIntNum()}}async getHeaderForHeight(t,e){const i=new se;i.writeVarIntNum(t.height);const r=await this.transmit("getHeaderForHeight",e,i.toArray());return{header:jt(r)}}async getNetwork(t,e){return{network:0===(await this.transmit("getNetwork",e))[0]?"mainnet":"testnet"}}async getVersion(t,e){const i=await this.transmit("getVersion",e);return{version:Yt(i)}}}class gr{baseUrl;httpClient;originator;constructor(t,e="http://localhost:3301",i=fetch){this.baseUrl=e,this.httpClient=i,this.originator=t}async transmitToWallet(t){const e=new ne(t),i=e.readUInt8(),r=fr[i];if(void 0===r||""===r)throw new Error(`Invalid call code: ${i}`);const s=e.readUInt8();let n;if(s>0){const t=e.read(s);n=Yt(t)}const a=e.read(),o=await fetch(`${this.baseUrl}/${r}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:n??""},body:new Uint8Array(a)}),c=await o.arrayBuffer();return Array.from(new Uint8Array(c))}}class yr extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(t,e,i,r,s){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=t,this.sendWithResults=e,this.txid=i,this.tx=r,this.noSendChange=s,this.code=5,this.name=this.constructor.name}}class br extends Error{parameter;code;isError=!0;constructor(t,e){super(`The ${t} parameter must be ${e??"valid."}`),this.parameter=t,this.code=6,this.name=this.constructor.name}}const mr=br;class wr extends Error{totalSatoshisNeeded;moreSatoshisNeeded;code;isError=!0;constructor(t,e){super(`Insufficient funds in the available inputs to cover the cost of the required outputs and the transaction fee (${e} more satoshis are needed, for a total of ${t}), plus whatever would be required in order to pay the fee to unlock and spend the outputs used to provide the additional satoshis.`),this.totalSatoshisNeeded=t,this.moreSatoshisNeeded=e,this.code=7,this.name=this.constructor.name}}const vr=wr;class Ir{baseUrl;httpClient;originator;api;constructor(t,e="http://localhost:3321",i=fetch){this.baseUrl=e,this.originator=t,this.httpClient=i;const r="undefined"!=typeof window&&"undefined"!=typeof document&&"file://"!==window?.origin;this.api=async(t,e)=>{const s=!r&&this.originator?function(t,e="http"){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(t))try{return new URL(t).origin}catch{}try{return new URL(`${e}://${t}`).origin}catch{throw new Error(`Invalid originator value: ${t}`)}}(this.originator,"http"):void 0;r||void 0!==s||console.error("Originator is required in Node.js environments");const n=await await i(`${this.baseUrl}/${t}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...s?{Origin:s}:{},...s?{Originator:s}:{}},body:JSON.stringify(e)}),a=await n.json();if(!n.ok){if(400===n.status&&a.isError){let t;switch(a.code){case 5:t=new yr(a.reviewActionResults,a.sendWithResults,a.txid,a.tx,a.noSendChange);break;case 6:t=new br(a.parameter),t.message=a.message;break;case 7:t=new vr(a.totalSatoshisNeeded,a.moreSatoshisNeeded)}if(t)throw t}const i={call:t,args:e,message:a.message??`HTTP Client error ${n.status}`};throw new Error(JSON.stringify(i))}return a}}async createAction(t){return await this.api("createAction",t)}async signAction(t){return await this.api("signAction",t)}async abortAction(t){return await this.api("abortAction",t)}async listActions(t){return await this.api("listActions",t)}async internalizeAction(t){return await this.api("internalizeAction",t)}async listOutputs(t){return await this.api("listOutputs",t)}async relinquishOutput(t){return await this.api("relinquishOutput",t)}async getPublicKey(t){return await this.api("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.api("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.api("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.api("encrypt",t)}async decrypt(t){return await this.api("decrypt",t)}async createHmac(t){return await this.api("createHmac",t)}async verifyHmac(t){return await this.api("verifyHmac",t)}async createSignature(t){return await this.api("createSignature",t)}async verifySignature(t){return await this.api("verifySignature",t)}async acquireCertificate(t){return await this.api("acquireCertificate",t)}async listCertificates(t){return await this.api("listCertificates",t)}async proveCertificate(t){return await this.api("proveCertificate",t)}async relinquishCertificate(t){return await this.api("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.api("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.api("discoverByAttributes",t)}async isAuthenticated(t){return await this.api("isAuthenticated",t)}async waitForAuthentication(t){return await this.api("waitForAuthentication",t)}async getHeight(t){return await this.api("getHeight",t)}async getHeaderForHeight(t){return await this.api("getHeaderForHeight",t)}async getNetwork(t){return await this.api("getNetwork",t)}async getVersion(t){return await this.api("getVersion",t)}}class kr{domain;constructor(t="*"){if("object"!=typeof window)throw new Error("The XDM substrate requires a global window object.");if(!window.hasOwnProperty("ReactNativeWebView"))throw new Error("The window object does not have a ReactNativeWebView property.");if("function"!=typeof window.ReactNativeWebView.postMessage)throw new Error("The window.ReactNativeWebView property does not seem to support postMessage calls.");this.domain=t}async invoke(t,e){return await new Promise((i,r)=>{const s=Zt(We(12)),n=t=>{const e=JSON.parse(t.data);if("CWI"===e.type&&e.id===s&&!0!==e.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",n),"error"===e.status){const t=new cr(e.description,e.code);r(t)}else i(e.result)};window.addEventListener("message",n),window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:s,call:t,args:e}))})}async createAction(t){return await this.invoke("createAction",t)}async signAction(t){return await this.invoke("signAction",t)}async abortAction(t){return await this.invoke("abortAction",t)}async listActions(t){return await this.invoke("listActions",t)}async internalizeAction(t){return await this.invoke("internalizeAction",t)}async listOutputs(t){return await this.invoke("listOutputs",t)}async relinquishOutput(t){return await this.invoke("relinquishOutput",t)}async getPublicKey(t){return await this.invoke("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.invoke("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.invoke("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.invoke("encrypt",t)}async decrypt(t){return await this.invoke("decrypt",t)}async createHmac(t){return await this.invoke("createHmac",t)}async verifyHmac(t){return await this.invoke("verifyHmac",t)}async createSignature(t){return await this.invoke("createSignature",t)}async verifySignature(t){return await this.invoke("verifySignature",t)}async acquireCertificate(t){return await this.invoke("acquireCertificate",t)}async listCertificates(t){return await this.invoke("listCertificates",t)}async proveCertificate(t){return await this.invoke("proveCertificate",t)}async relinquishCertificate(t){return await this.invoke("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.invoke("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.invoke("discoverByAttributes",t)}async isAuthenticated(t){return await this.invoke("isAuthenticated",t)}async waitForAuthentication(t){return await this.invoke("waitForAuthentication",t)}async getHeight(t){return await this.invoke("getHeight",t)}async getHeaderForHeight(t){return await this.invoke("getHeaderForHeight",t)}async getNetwork(t){return await this.invoke("getNetwork",t)}async getVersion(t){return await this.invoke("getVersion",t)}}function Sr(t){const[e,i]=t.split(".");return{txid:e,vout:Number(i)}}function Er(t){return t??!0}function xr(t){return t??!1}function _r(t){return t??0}function Pr(t){return t??[]}function Ar(t,e,i,r){if(void 0!==t)return Cr(t,e,i,r)}function Nr(t,e,i){if(void 0===t||!Number.isInteger(t)||t<0||t>21e14)throw new mr(e,"a valid number of satoshis");if(void 0!==i&&t<i)throw new mr(e,`at least ${i} satoshis.`);return t}function Or(t,e,i,r,s){if(void 0===t){if(void 0!==i)return i;throw new mr(e,"a valid integer")}if(!Number.isInteger(t))throw new mr(e,"an integer");if(t=Number(t),void 0!==r&&t<r)throw new mr(e,`at least ${r} length.`);if(void 0!==s&&t>s)throw new mr(e,`no more than ${s} length.`);return t}function Tr(t,e){return Or(t,e,0,0)}function Cr(t,e,i,r){const s=Wt(t,"utf8").length;if(void 0!==i&&s<i)throw new mr(e,`at least ${i} length.`);if(void 0!==r&&s>r)throw new mr(e,`no more than ${r} length.`);return t}function Rr(t){if(void 0!==t)return Br(t)}function Br(t){return Fr(t,"basket",1,300)}function Lr(t){return Fr(t,"label",1,300)}function Mr(t){return Fr(t,"tag",1,300)}function Fr(t,e,i,r){t=t.trim().toLowerCase();const s=Wt(t,"utf8").length;if(void 0!==i&&s<i)throw new mr(e,`at least ${i} length.`);if(void 0!==r&&s>r)throw new mr(e,`no more than ${r} length.`);return t}function Ur(t,e,i,r){if(void 0!==t)return Dr(t,e,i,r)}function Dr(t,e,i,r){if(0===(t=t.trim()).length)throw new mr(e,"valid base64 string");let s=0;for(let i=0;i<t.length;i++){const r=t.charCodeAt(i);if(!(r>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r)){if(61!==r)throw new mr(e,"valid base64 string");if(i<t.length-2)throw new mr(e,"valid base64 string");s++}}if(s>2)throw new mr(e,"valid base64 string");if(s>0&&t.length%4!=0)throw new mr(e,"valid base64 string");const n=t.length%4;if(0!==n&&n!==4-s)throw new mr(e,"valid base64 string");const a=t.length-s,o=Math.floor(3*a/4);if(void 0!==i&&o<i)throw new mr(e,`at least ${i} bytes`);if(void 0!==r&&o>r)throw new mr(e,`no more than ${r} bytes`);return t}function Hr(t,e,i,r){if(void 0!==t)return qr(t,e,i,r)}function qr(t,e,i,r){if((t=t.trim().toLowerCase()).length%2==1)throw new mr(e,`even length, not ${t.length}.`);if(!/^[0-9A-Fa-f]+$/.test(t))throw new mr(e,"hexadecimal string.");if(void 0!==i&&t.length<i)throw new mr(e,`at least ${i} length.`);if(void 0!==r&&t.length>r)throw new mr(e,`no more than ${r} length.`);return t}function Vr(t){const e=null!=t?t:{};return{signAndProcess:Er(e.signAndProcess),acceptDelayedBroadcast:Er(e.acceptDelayedBroadcast),knownTxids:Pr(e.knownTxids),returnTXIDOnly:xr(e.returnTXIDOnly),noSend:xr(e.noSend),noSendChange:Pr(e.noSendChange).map(t=>Sr(t)),sendWith:Pr(e.sendWith),randomizeOutputs:Er(e.randomizeOutputs)}}function Kr(t){const e=null!=t?t:{};return{acceptDelayedBroadcast:Er(e.acceptDelayedBroadcast),returnTXIDOnly:xr(e.returnTXIDOnly),noSend:xr(e.noSend),sendWith:Pr(e.sendWith)}}function $r(t){if(void 0!==t)return{derivationPrefix:Dr(t.derivationPrefix,"derivationPrefix"),derivationSuffix:Dr(t.derivationSuffix,"derivationSuffix"),senderIdentityKey:qr(t.senderIdentityKey,"senderIdentityKey")}}function jr(t){if(void 0!==t)return{basket:Br(t.basket),customInstructions:Ar(t.customInstructions,"customInstructions",0,1e3),tags:Pr(t.tags).map(t=>Mr(t))}}function zr(t,e){const i=t.split(".");if(2!==i.length||!Number.isInteger(Number(i[1])))throw new mr(e,"txid as hex string and numeric output index joined with '.'");return`${qr(i[0],`${e} txid`,void 0,64)}.${Tr(Number(i[1]),`${e} vout`)}`}function Wr(t){for(const e of Object.keys(t))Cr(e,"field name",1,50);return t}const Gr="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";class Xr{substrate;originator;constructor(t="auto",e){"Cicada"===t&&(t=new pr(new gr(e))),"window.CWI"===t&&(t=new or),"XDM"===t&&(t=new dr),"json-api"===t&&(t=new Ir(e)),"react-native"===t&&(t=new kr(e)),"secure-json-api"===t&&(t=new Ir(e,"https://localhost:2121")),this.substrate=t,this.originator=e}async connectToSubstrate(){if("object"==typeof this.substrate)return;const t=async(t,e)=>{try{const i=t();let r;return r="number"==typeof e?await Promise.race([i.getVersion({}),new Promise((t,i)=>setTimeout(()=>i(new Error("Timed out.")),e))]):await i.getVersion({}),"object"!=typeof r||"string"!=typeof r.version?{success:!1}:{success:!0,sub:i}}catch{return{success:!1}}},e=[t(()=>new or),t(()=>new pr(new gr(this.originator))),t(()=>new Ir(this.originator,"https://localhost:2121")),t(()=>new Ir(this.originator)),t(()=>new kr(this.originator))],i=(await Promise.allSettled(e)).filter(t=>"fulfilled"===t.status&&t.value.success&&void 0!==t.value.sub).map(t=>t.value.sub);if(i.length>0)return void(this.substrate=i[0]);const r=await t(()=>new dr,200);if(!r.success||void 0===r.sub)throw new Error("No wallet available over any communication substrate. Install a BSV wallet today!");this.substrate=r.sub}async createAction(t){return function(t,e){const i={description:Cr(t.description,"description",5,2e3),inputBEEF:t.inputBEEF,inputs:Pr(t.inputs).map(t=>function(t){if(void 0===t.unlockingScript&&void 0===t.unlockingScriptLength)throw new mr("unlockingScript, unlockingScriptLength","at least one valid value.");const e=Hr(t.unlockingScript,"unlockingScript"),i=t.unlockingScriptLength??(null!=e?e.length/2:0);if(e&&i!==e.length/2)throw new mr("unlockingScriptLength","length unlockingScript if both valid.");var r;return{outpoint:Sr(t.outpoint),inputDescription:Cr(t.inputDescription,"inputDescription",5,2e3),unlockingScript:e,unlockingScriptLength:i,sequenceNumber:(r=t.sequenceNumber,r??4294967295)}}(t)),outputs:Pr(t.outputs).map(t=>function(t){return{lockingScript:qr(t.lockingScript,"lockingScript"),satoshis:Nr(t.satoshis,"satoshis"),outputDescription:Cr(t.outputDescription,"outputDescription",5,2e3),basket:Rr(t.basket),customInstructions:t.customInstructions,tags:Pr(t.tags).map(t=>Mr(t))}}(t)),lockTime:_r(t.lockTime),version:(r=t.version,r??1),labels:Pr(t.labels?.map(t=>Lr(t))),options:Vr(t.options),logger:e,isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!1,isRemixChange:!1,isSignAction:!1,randomVals:void 0,includeAllSourceTransactions:!1,isTestWerrReviewActions:!1};var r;i.isTestWerrReviewActions=i.labels.includes(Gr),i.isSendWith=i.options.sendWith.length>0,i.isRemixChange=!i.isSendWith&&0===i.inputs.length&&0===i.outputs.length,i.isNewTx=i.isRemixChange||i.inputs.length>0||i.outputs.length>0,i.isSignAction=i.isNewTx&&(!i.options.signAndProcess||i.inputs.some(t=>void 0===t.unlockingScript)),i.isDelayed=i.options.acceptDelayedBroadcast,i.isNoSend=i.options.noSend}(t),await this.connectToSubstrate(),await this.substrate.createAction(t,this.originator)}async signAction(t){return function(t){const e={spends:t.spends,reference:t.reference,options:Kr(t.options),isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!0,isRemixChange:!1,isTestWerrReviewActions:!1};e.isSendWith=e.options.sendWith.length>0,e.isDelayed=e.options.acceptDelayedBroadcast,e.isNoSend=e.options.noSend}(t),await this.connectToSubstrate(),await this.substrate.signAction(t,this.originator)}async abortAction(t){return function(t){Dr(t.reference,"reference")}(t),await this.connectToSubstrate(),await this.substrate.abortAction(t,this.originator)}async listActions(t){return function(t){let e;if(void 0===t.labelQueryMode||"any"===t.labelQueryMode)e="any";else{if("all"!==t.labelQueryMode)throw new mr("labelQueryMode","undefined, 'any', or 'all'");e="all"}(null!=t.labels?t.labels:[]).map(t=>Lr(t)),xr(t.includeLabels),xr(t.includeInputs),xr(t.includeInputSourceLockingScripts),xr(t.includeInputUnlockingScripts),xr(t.includeOutputs),xr(t.includeOutputLockingScripts),Or(t.limit,"limit",10,1,1e4),Or(t.offset,"offset",0,0),Er(t.seekPermission)}(t),await this.connectToSubstrate(),await this.substrate.listActions(t,this.originator)}async internalizeAction(t){return function(t){const e={tx:t.tx,outputs:t.outputs.map(t=>function(t){if("basket insertion"!==t.protocol&&"wallet payment"!==t.protocol)throw new mr("protocol","'basket insertion' or 'wallet payment'");return{outputIndex:Tr(t.outputIndex,"outputIndex"),protocol:t.protocol,paymentRemittance:$r(t.paymentRemittance),insertionRemittance:jr(t.insertionRemittance)}}(t)),description:Cr(t.description,"description",5,2e3),labels:(null!=t.labels?t.labels:[]).map(t=>Lr(t)),seekPermission:Er(t.seekPermission)};try{if(er.fromBinary(e.tx).txs.length<1)throw new mr("tx","at least one transaction to internalize an output from")}catch{throw new mr("tx","valid with at least one transaction to internalize an output from")}if(e.outputs.length<1)throw new mr("outputs","at least one output to internalize from the transaction")}(t),await this.connectToSubstrate(),await this.substrate.internalizeAction(t,this.originator)}async listOutputs(t){return function(t){let e;if(void 0===t.tagQueryMode||"any"===t.tagQueryMode)e="any";else{if("all"!==t.tagQueryMode)throw new mr("tagQueryMode","undefined, 'any', or 'all'");e="all"}Cr(t.basket,"basket",1,300),(null!=t.tags?t.tags:[]).map(t=>Cr(t,"tag",1,300)),t.include,t.include,xr(t.includeCustomInstructions),xr(t.includeTags),xr(t.includeLabels),Or(t.limit,"limit",10,1,1e4),Or(t.offset,"offset",0,void 0,void 0),Er(t.seekPermission)}(t),await this.connectToSubstrate(),await this.substrate.listOutputs(t,this.originator)}async relinquishOutput(t){return function(t){Br(t.basket),zr(t.output,"output")}(t),await this.connectToSubstrate(),await this.substrate.relinquishOutput(t,this.originator)}async getPublicKey(t){return await this.connectToSubstrate(),await this.substrate.getPublicKey(t,this.originator)}async revealCounterpartyKeyLinkage(t){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(t,this.originator)}async revealSpecificKeyLinkage(t){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(t,this.originator)}async encrypt(t){return await this.connectToSubstrate(),await this.substrate.encrypt(t,this.originator)}async decrypt(t){return await this.connectToSubstrate(),await this.substrate.decrypt(t,this.originator)}async createHmac(t){return await this.connectToSubstrate(),await this.substrate.createHmac(t,this.originator)}async verifyHmac(t){return await this.connectToSubstrate(),await this.substrate.verifyHmac(t,this.originator)}async createSignature(t){return await this.connectToSubstrate(),await this.substrate.createSignature(t,this.originator)}async verifySignature(t){return await this.connectToSubstrate(),await this.substrate.verifySignature(t,this.originator)}async acquireCertificate(t){if("direct"===t.acquisitionProtocol)!function(t){if("direct"!==t.acquisitionProtocol)throw new Error("Only acquire direct certificate requests allowed here.");if(!t.serialNumber)throw new mr("serialNumber",'valid when acquisitionProtocol is "direct"');if(!t.signature)throw new mr("signature",'valid when acquisitionProtocol is "direct"');if(!t.revocationOutpoint)throw new mr("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!t.keyringRevealer)throw new mr("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null==t.keyringForSubject)throw new mr("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(t.privileged&&!t.privilegedReason)throw new mr("privilegedReason","valid when 'privileged' is true ");var e;Dr(t.type,"type"),Dr(t.serialNumber,"serialNumber"),qr(t.certifier,"certifier"),zr(t.revocationOutpoint,"revocationOutpoint"),Wr(t.fields),qr(t.signature,"signature"),"certifier"===(e=t.keyringRevealer)||qr(e,"keyringRevealer"),function(t,e){for(const i of Object.keys(t))Cr(i,`${e} field name`,1,50),Dr(t[i],`${e} field value`)}(t.keyringForSubject,"keyringForSubject"),xr(t.privileged),Ar(t.privilegedReason,"privilegedReason",5,50)}(t);else{if("issuance"!==t.acquisitionProtocol)throw new br("acquisitionProtocol",`valid. ${String(t.acquisitionProtocol)} is unrecognized.`);!function(t){if("issuance"!==t.acquisitionProtocol)throw new Error("Only acquire certificate via issuance requests allowed here.");if(t.serialNumber)throw new mr("serialNumber",'valid when acquisitionProtocol is "direct"');if(t.signature)throw new mr("signature",'valid when acquisitionProtocol is "direct"');if(t.revocationOutpoint)throw new mr("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(t.keyringRevealer)throw new mr("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null!=t.keyringForSubject)throw new mr("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!t.certifierUrl)throw new mr("certifierUrl",'valid when acquisitionProtocol is "issuance"');if(t.privileged&&!t.privilegedReason)throw new mr("privilegedReason","valid when 'privileged' is true ");Dr(t.type,"type"),qr(t.certifier,"certifier"),t.certifierUrl,Wr(t.fields),xr(t.privileged),Ar(t.privilegedReason,"privilegedReason",5,50)}(t)}return await this.connectToSubstrate(),await this.substrate.acquireCertificate(t,this.originator)}async listCertificates(t){return function(t){Pr(t.certifiers.map(t=>qr(t.trim(),"certifiers"))),Pr(t.types.map(t=>Dr(t.trim(),"types"))),Or(t.limit,"limit",10,1,1e4),Tr(_r(t.offset),"offset"),xr(t.privileged),Ar(t.privilegedReason,"privilegedReason",5,50)}(t),await this.connectToSubstrate(),await this.substrate.listCertificates(t,this.originator)}async proveCertificate(t){return function(t){if(t.privileged&&!t.privilegedReason)throw new mr("privilegedReason","valid when 'privileged' is true ");Ur(t.certificate.type,"certificate.type"),Ur(t.certificate.serialNumber,"certificate.serialNumber"),Hr(t.certificate.certifier,"certificate.certifier"),Hr(t.certificate.subject,"certificate.subject"),function(t,e){if(void 0!==t)zr(t,e)}(t.certificate.revocationOutpoint,"certificate.revocationOutpoint"),Hr(t.certificate.signature,"certificate.signature"),Pr(t.fieldsToReveal).map(t=>Cr(t,`fieldsToReveal ${t}`,1,50)),qr(t.verifier,"verifier"),xr(t.privileged),Ar(t.privilegedReason,"privilegedReason",5,50)}(t),await this.connectToSubstrate(),await this.substrate.proveCertificate(t,this.originator)}async relinquishCertificate(t){return function(t){Dr(t.type,"type"),Dr(t.serialNumber,"serialNumber"),qr(t.certifier,"certifier")}(t),await this.connectToSubstrate(),await this.substrate.relinquishCertificate(t,this.originator)}async discoverByIdentityKey(t){return function(t){qr(t.identityKey,"identityKey",66,66),Or(t.limit,"limit",10,1,1e4),Tr(_r(t.offset),"offset"),xr(t.seekPermission)}(t),await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(t,this.originator)}async discoverByAttributes(t){return function(t){(function(t){for(const e of Object.keys(t))Cr(e,`field name ${e}`,1,50)})(t.attributes),Or(t.limit,"limit",10,1,1e4),Tr(_r(t.offset),"offset"),xr(t.seekPermission)}(t),await this.connectToSubstrate(),await this.substrate.discoverByAttributes(t,this.originator)}async isAuthenticated(t={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(t,this.originator)}async waitForAuthentication(t={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(t,this.originator)}async getHeight(t={}){return await this.connectToSubstrate(),await this.substrate.getHeight(t,this.originator)}async getHeaderForHeight(t){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(t,this.originator)}async getNetwork(t={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(t,this.originator)}async getVersion(t={}){return await this.connectToSubstrate(),await this.substrate.getVersion(t,this.originator)}}class Yr extends lr{keyring;decryptedFields;constructor(t,e,i,r,s,n,a,o,c){super(t,e,i,r,s,n,o),this.keyring=a,this.decryptedFields=c}static fromCertificate(t,e){return new Yr(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,e,t.signature)}async decryptFields(t,e,i,r){if(null==this.keyring||0===Object.keys(this.keyring).length)throw new Error("A keyring is required to decrypt certificate fields for the verifier.");try{const s={};for(const n in this.keyring){const{plaintext:a}=await t.decrypt({ciphertext:Wt(this.keyring[n],"base64"),...lr.getCertificateFieldEncryptionDetails(n,this.serialNumber),counterparty:this.subject,privileged:e,privilegedReason:i},r),o=new wi(a).decrypt(Wt(this.fields[n],"base64"));s[n]=Yt(o)}return s}catch(t){throw new Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(t instanceof Error?t.message:t)}`)}}}class Jr{sessionNonceToSession;identityKeyToNonces;constructor(){this.sessionNonceToSession=new Map,this.identityKeyToNonces=new Map}addSession(t){if("string"!=typeof t.sessionNonce)throw new Error("Invalid session: sessionNonce is required to add a session.");if(this.sessionNonceToSession.set(t.sessionNonce,t),"string"==typeof t.peerIdentityKey){let e=this.identityKeyToNonces.get(t.peerIdentityKey);null==e&&(e=new Set,this.identityKeyToNonces.set(t.peerIdentityKey,e)),e.add(t.sessionNonce)}}updateSession(t){this.removeSession(t),this.addSession(t)}getSession(t){const e=this.sessionNonceToSession.get(t);if(null!=e)return e;const i=this.identityKeyToNonces.get(t);if(null==i||0===i.size)return;let r;for(const t of i){const e=this.sessionNonceToSession.get(t);null!=e&&(null==r||(e.lastUpdate??0)>(r.lastUpdate??0))&&(r=e)}return r}removeSession(t){if("string"==typeof t.sessionNonce&&this.sessionNonceToSession.delete(t.sessionNonce),"string"==typeof t.peerIdentityKey){const e=this.identityKeyToNonces.get(t.peerIdentityKey);null!=e&&(e.delete(t.sessionNonce??""),0===e.size&&this.identityKeyToNonces.delete(t.peerIdentityKey))}}hasSession(t){if(this.sessionNonceToSession.has(t))return!0;const e=this.identityKeyToNonces.get(t);return!(null==e)&&e.size>0}}async function Zr(t,e,i="self",r){const s=Wt(t,"base64"),n=s.slice(0,16),a=s.slice(16),{valid:o}=await e.verifyHmac({data:n,hmac:a,protocolID:[2,"server hmac"],keyID:Yt(n),counterparty:i},r);return o}async function Qr(t,e="self",i){const r=We(16),{hmac:s}=await t.createHmac({protocolID:[2,"server hmac"],keyID:Yt(r),data:r,counterparty:e},i);return Zt([...r,...s])}const ts=async(t,e,i,r)=>{const s=await t.listCertificates({certifiers:e.certifiers,types:Object.keys(e.types)},r);return await Promise.all(s.certificates.map(async s=>{const{keyringForVerifier:n}=await t.proveCertificate({certificate:s,fieldsToReveal:e.types[s.type],verifier:i},r);return new Yr(s.type,s.serialNumber,s.subject,s.certifier,s.revocationOutpoint,s.fields,n,s.signature)}))},es=async(t,e,i,r)=>{if(null==e.certificates||0===e.certificates.length)throw new Error("No certificates were provided in the AuthMessage.");await Promise.all(e.certificates.map(async s=>{if(s.subject!==e.identityKey)throw new Error(`The subject of one of your certificates ("${s.subject}") is not the same as the request sender ("${e.identityKey}").`);const n=new Yr(s.type,s.serialNumber,s.subject,s.certifier,s.revocationOutpoint,s.fields,s.keyring,s.signature);if(!await n.verify())throw new Error(`The signature for the certificate with serial number ${n.serialNumber} is invalid!`);if(null!=i){const{certifiers:t,types:e}=i;if(!t.includes(n.certifier))throw new Error(`Certificate with serial number ${n.serialNumber} has an unrequested certifier: ${n.certifier}`);if(null==e[n.type])throw new Error(`Certificate with type ${n.type} was not requested`)}await n.decryptFields(t,void 0,void 0,r)}))},is="0.1",rs="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class ss{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;certificateValidationPromises=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;identityPublicKey;constructor(t,e,i,r,s,n){this.wallet=t,this.originator=n,this.transport=e,this.certificatesToRequest=i??{certifiers:[],types:{}},this.transport.onData(this.handleIncomingMessage.bind(this)).catch(t=>{throw t}),this.sessionManager=null!=r?r:new Jr,this.autoPersistLastSession=!1!==s}async toPeer(t,e){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof e&&(e=this.lastInteractedWithPeer);const i=await this.getAuthenticatedSession(e);if(null==i.peerIdentityKey)throw new Error("Peer identity is not established");if(!0===i.certificatesRequired&&!0!==i.certificatesValidated)throw new Error("Cannot send general message before certificate validation is complete");const r=Zt(We(32)),{signature:s}=await this.wallet.createSignature({data:t,protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),n={version:is,messageType:"general",identityKey:await this.getIdentityPublicKey(),nonce:r,yourNonce:i.peerNonce,payload:t,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(n)}catch(t){this.propagateTransportError(i.peerIdentityKey,t)}}async requestCertificates(t,e){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof e&&(e=this.lastInteractedWithPeer);const i=await this.getAuthenticatedSession(e),r=Zt(We(32)),{signature:s}=await this.wallet.createSignature({data:ss.utf8ToBytes(JSON.stringify(t)),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),n={version:is,messageType:"certificateRequest",identityKey:await this.getIdentityPublicKey(),nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:t,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(n)}catch(t){this.propagateTransportError(i.peerIdentityKey,t)}}async getAuthenticatedSession(t){if(void 0===this.transport)throw new Error("Peer transport is not connected!");let e;if("string"==typeof t&&(e=this.sessionManager.getSession(t)),null==e||!e.isAuthenticated){const i=await this.initiateHandshake(t);if(e=this.sessionManager.getSession(i),null==e||!e.isAuthenticated)throw new Error("Unable to establish mutual authentication with peer!")}return e}listenForGeneralMessages(t){const e=this.callbackIdCounter++;return this.onGeneralMessageReceivedCallbacks.set(e,t),e}stopListeningForGeneralMessages(t){this.onGeneralMessageReceivedCallbacks.delete(t)}listenForCertificatesReceived(t){const e=this.callbackIdCounter++;return this.onCertificatesReceivedCallbacks.set(e,t),e}stopListeningForCertificatesReceived(t){this.onCertificatesReceivedCallbacks.delete(t)}listenForCertificatesRequested(t){const e=this.callbackIdCounter++;return this.onCertificateRequestReceivedCallbacks.set(e,t),e}stopListeningForCertificatesRequested(t){this.onCertificateRequestReceivedCallbacks.delete(t)}async initiateHandshake(t){const e=await Qr(this.wallet,void 0,this.originator),i=Date.now(),r=this.certificatesToRequest.certifiers.length>0;this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:e,peerIdentityKey:t,lastUpdate:i,certificatesRequired:r,certificatesValidated:!r});const s={version:is,messageType:"initialRequest",identityKey:await this.getIdentityPublicKey(),initialNonce:e,requestedCertificates:this.certificatesToRequest};return await this.transport.send(s),await this.waitForInitialResponse(e)}async waitForInitialResponse(t){return await new Promise(e=>{const i=this.listenForInitialResponse(t,t=>{this.stopListeningForInitialResponses(i),e(t)})})}listenForInitialResponse(t,e){const i=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(i,{callback:e,sessionNonce:t}),i}stopListeningForInitialResponses(t){this.onInitialResponseReceivedCallbacks.delete(t)}propagateTransportError(t,e){if(e instanceof Error){if(null!=t){const i=e.details;null!=i&&"object"==typeof i?null==i.peerIdentityKey&&(i.peerIdentityKey=t):e.details={peerIdentityKey:t}}throw e}const i=`Failed to send message to peer ${t??"unknown"}: ${String(e)}`;throw new Error(i)}async handleIncomingMessage(t){if("string"!=typeof t.version||t.version!==is)throw new Error(`Invalid or unsupported message auth version! Received: ${t.version}, expected: ${is}`);try{switch(t.messageType){case"initialRequest":await this.processInitialRequest(t);break;case"initialResponse":await this.processInitialResponse(t);break;case"certificateRequest":await this.processCertificateRequest(t);break;case"certificateResponse":await this.processCertificateResponse(t);break;case"general":await this.processGeneralMessage(t);break;default:throw new Error(`Unknown message type of ${String(t.messageType)} from ${String(t.identityKey)}`)}}catch(t){}}async processInitialRequest(t){if("string"!=typeof t.identityKey||"string"!=typeof t.initialNonce||""===t.initialNonce)throw new Error("Missing required fields in initialRequest message.");const e=await Qr(this.wallet,void 0,this.originator),i=Date.now(),r=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0;let s;this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:e,peerNonce:t.initialNonce,peerIdentityKey:t.identityKey,lastUpdate:i,certificatesRequired:r,certificatesValidated:!r}),Array.isArray(t.requestedCertificates?.certifiers)&&t.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach(e=>{e(t.identityKey,t.requestedCertificates)}):s=await ts(this.wallet,t.requestedCertificates,t.identityKey,this.originator));const{signature:n}=await this.wallet.createSignature({data:[...ss.base64ToBytes(t.initialNonce),...ss.base64ToBytes(e)],protocolID:[2,"auth message signature"],keyID:`${t.initialNonce} ${e}`,counterparty:t.identityKey},this.originator),a={version:is,messageType:"initialResponse",identityKey:await this.getIdentityPublicKey(),initialNonce:e,yourNonce:t.initialNonce,certificates:s,requestedCertificates:this.certificatesToRequest,signature:n};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=t.identityKey),await this.transport.send(a)}async processInitialResponse(t){if(!await Zr(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Initial response nonce verification failed from peer: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Peer session not found for peer: ${t.identityKey}`);const i=ss.base64ToBytes((e.sessionNonce??"")+(t.initialNonce??"")),{valid:r}=await this.wallet.verifySignature({data:i,signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${e.sessionNonce??""} ${t.initialNonce??""}`,counterparty:t.identityKey},this.originator);if(!r)throw new Error(`Unable to verify initial response signature for peer: ${t.identityKey}`);if(e.peerNonce=t.initialNonce,e.peerIdentityKey=t.identityKey,e.isAuthenticated=!0,e.certificatesRequired=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0,e.certificatesValidated=!e.certificatesRequired,e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),e.certificatesRequired&&Array.isArray(t.certificates)&&t.certificates.length>0&&(await es(this.wallet,t,this.certificatesToRequest,this.originator),e.certificatesValidated=!0,e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),null!=e.sessionNonce&&this.resolveCertificateValidation(e.sessionNonce),this.onCertificatesReceivedCallbacks.forEach(e=>e(t.identityKey,t.certificates))),this.lastInteractedWithPeer=t.identityKey,this.onInitialResponseReceivedCallbacks.forEach(t=>{t.sessionNonce===e.sessionNonce&&t.callback(e.sessionNonce)}),null!=t.requestedCertificates&&Array.isArray(t.requestedCertificates.certifiers)&&t.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(e=>{e(t.identityKey,t.requestedCertificates)});else{const e=await ts(this.wallet,t.requestedCertificates,t.identityKey,this.originator);await this.sendCertificateResponse(t.identityKey,e)}}async processCertificateRequest(t){if(!await Zr(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for certificate request message from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{valid:i}=await this.wallet.verifySignature({data:ss.utf8ToBytes(JSON.stringify(t.requestedCertificates)),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:e.peerIdentityKey},this.originator);if(!i)throw new Error(`Invalid signature in certificate request message from ${e.peerIdentityKey}`);if(e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),null!=t.requestedCertificates&&Array.isArray(t.requestedCertificates.certifiers)&&t.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(e=>{e(t.identityKey,t.requestedCertificates)});else{const e=await ts(this.wallet,t.requestedCertificates,t.identityKey,this.originator);await this.sendCertificateResponse(t.identityKey,e)}}async sendCertificateResponse(t,e){const i=await this.getAuthenticatedSession(t),r=Zt(We(32)),{signature:s}=await this.wallet.createSignature({data:ss.utf8ToBytes(JSON.stringify(e)),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),n={version:is,messageType:"certificateResponse",identityKey:await this.getIdentityPublicKey(),nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,certificates:e,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(n)}catch(t){this.propagateTransportError(i.peerIdentityKey,t)}}async processCertificateResponse(t){if(!await Zr(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for certificate response from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{valid:i}=await this.wallet.verifySignature({data:ss.utf8ToBytes(JSON.stringify(t.certificates)),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:t.identityKey},this.originator);if(!i)throw new Error(`Unable to verify certificate response signature for peer: ${t.identityKey}`);await es(this.wallet,t,t.requestedCertificates,this.originator),e.certificatesValidated=!0,e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),null!=e.sessionNonce&&this.resolveCertificateValidation(e.sessionNonce),this.onCertificatesReceivedCallbacks.forEach(e=>{e(t.identityKey,t.certificates??[])})}async processGeneralMessage(t){if(!await Zr(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for general message from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const i=!0===e.certificatesRequired,r=!0===e.certificatesValidated;if(i&&!r){const t=3e4,i=e.sessionNonce;if(null==i)throw new Error("Session nonce is required for certificate validation");await new Promise((r,s)=>{const n=setTimeout(()=>{null!=this.certificateValidationPromises.get(i)&&(this.certificateValidationPromises.delete(i),s(new Error(`Timeout waiting for certificate validation from peer ${e.peerIdentityKey??"unknown"}`)))},t);"object"==typeof n&&"unref"in n&&n.unref(),this.certificateValidationPromises.set(i,{resolve:()=>{clearTimeout(n),r()},reject:t=>{clearTimeout(n),s(t)}})})}const{valid:s}=await this.wallet.verifySignature({data:t.payload,signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:e.peerIdentityKey},this.originator);if(!s)throw new Error(`Invalid signature in generalMessage from ${e.peerIdentityKey}`);e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),this.lastInteractedWithPeer=t.identityKey,this.onGeneralMessageReceivedCallbacks.forEach(e=>{e(t.identityKey,t.payload??[])})}resolveCertificateValidation(t){const e=this.certificateValidationPromises.get(t);null!=e&&(e.resolve(),this.certificateValidationPromises.delete(t))}async getIdentityPublicKey(){if(null!=this.identityPublicKey)return this.identityPublicKey;const{publicKey:t}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return this.identityPublicKey=t,t}static utf8ToBytes(t){return null!=rs?Array.from(rs.from(t,"utf8")):"undefined"!=typeof TextEncoder?Array.from((new TextEncoder).encode(t)):Wt(t,"utf8")}static base64ToBytes(t){return null!=rs?Array.from(rs.from(t,"base64")):Wt(t,"base64")}}const ns="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch;class as{onDataCallback;fetchClient;baseUrl;constructor(t,e=ns){if("function"!=typeof e)throw new Error("SimplifiedFetchTransport requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=e,this.baseUrl=t}async send(t){if(null==this.onDataCallback)throw new Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==t.messageType)return await new Promise((e,i)=>{(async()=>{try{const i=`${this.baseUrl}/.well-known/auth`,r=(async()=>{try{return await this.fetchClient(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(t){throw this.createNetworkError(i,t)}})();"initialRequest"!==t.messageType&&e();const s=await r;if(!s.ok){const t=Array.from(new Uint8Array(await s.arrayBuffer()));throw this.createUnauthenticatedResponseError(i,s,t)}if(null!=this.onDataCallback){const t=await s.json();this.onDataCallback(t)}"initialRequest"===t.messageType&&e()}catch(t){i(t)}})()});{const e=this.deserializeRequestPayload(t.payload),i=`${this.baseUrl}${e.urlPostfix}`,r=e;if("object"!=typeof e.headers&&(r.headers={}),r.headers["x-bsv-auth-version"]=t.version,r.headers["x-bsv-auth-identity-key"]=t.identityKey,r.headers["x-bsv-auth-nonce"]=t.nonce,r.headers["x-bsv-auth-your-nonce"]=t.yourNonce,r.headers["x-bsv-auth-signature"]=jt(t.signature),r.headers["x-bsv-auth-request-id"]=e.requestId,null!=r.body){const t=r.headers;if(null==t["content-type"])throw new Error("Content-Type header is required for requests with a body.");const e=String(t["content-type"]??"");e.includes("application/json")||e.includes("application/x-www-form-urlencoded")||e.includes("text/plain")?r.body=Yt(r.body):r.body=new Uint8Array(r.body)}let s;try{s=await this.fetchClient(i,{method:r.method,headers:r.headers,body:r.body})}catch(t){throw this.createNetworkError(i,t)}const n=await s.arrayBuffer(),a=Array.from(new Uint8Array(n)),o=["x-bsv-auth-version","x-bsv-auth-identity-key","x-bsv-auth-signature"].filter(t=>{const e=s.headers.get(t);return null==e||0===e.trim().length});if(o.length>0)throw this.createUnauthenticatedResponseError(i,s,a,o);const c=s.headers.get("x-bsv-auth-requested-certificates");let h;if(null!=c)try{h=JSON.parse(c)}catch(t){throw this.createMalformedHeaderError(i,"x-bsv-auth-requested-certificates",c,t)}const u=new se;null!=s.headers.get("x-bsv-auth-request-id")&&u.write(Wt(s.headers.get("x-bsv-auth-request-id"),"base64")),u.writeVarIntNum(s.status);const d=[];s.headers.forEach((t,e)=>{const i=e.toLowerCase();!i.startsWith("x-bsv-")&&"authorization"!==i||i.startsWith("x-bsv-auth")||d.push([i,t])}),d.sort(([t],[e])=>t.localeCompare(e)),u.writeVarIntNum(d.length);for(let t=0;t<d.length;t++){const e=Wt(d[t][0],"utf8");u.writeVarIntNum(e.length),u.write(e);const i=Wt(d[t][1],"utf8");u.writeVarIntNum(i.length),u.write(i)}u.writeVarIntNum(a.length),a.length>0&&u.write(a);const l={version:s.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===s.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:s.headers.get("x-bsv-auth-identity-key"),nonce:s.headers.get("x-bsv-auth-nonce")??void 0,yourNonce:s.headers.get("x-bsv-auth-your-nonce")??void 0,requestedCertificates:h,payload:u.toArray(),signature:Wt(s.headers.get("x-bsv-auth-signature"),"hex")};if(null==l.version)throw this.createUnauthenticatedResponseError(i,s,a);this.onDataCallback(l)}}async onData(t){this.onDataCallback=e=>{t(e)}}createNetworkError(t,e){const i=`Network error while sending authenticated request to ${t}`;if(e instanceof Error){const t=new Error(`${i}: ${e.message}`);return t.stack=e.stack,t.cause=e,t}return new Error(`${i}: ${String(e)}`)}createUnauthenticatedResponseError(t,e,i,r=[]){const s=(e.statusText??"").trim(),n=s.length>0?`${e.status} ${s}`:`${e.status}`,a=r.length>0?`missing headers: ${r.join(", ")}`:"response lacked required BSV auth headers",o=this.getBodyPreview(i,e.headers.get("content-type")),c=[`Received HTTP ${n} from ${t} without valid BSV authentication (${a})`];null!=o&&c.push(`body preview: ${o}`);const h=new Error(c.join(" - "));return h.details={url:t,status:e.status,statusText:e.statusText,missingHeaders:r,bodyPreview:o},h}createMalformedHeaderError(t,e,i,r){const s=`Failed to parse ${e} returned by ${t}: ${i}`;if(r instanceof Error){const t=new Error(`${s}. ${r.message}`);return t.stack=r.stack,t.cause=r,t}return new Error(`${s}. ${String(r)}`)}getBodyPreview(t,e){if(0===t.length)return;const i=t.length>1024,r=i?t.slice(0,1024):t;let s;if(this.isTextualContent(e,r))try{s=Yt(r)}catch{s=this.formatBinaryPreview(r,i)}else s=this.formatBinaryPreview(r,i);return s.length>512&&(s=`${s.slice(0,512)}…`),i&&(s=`${s} (truncated)`),s}isTextualContent(t,e){if(0===e.length)return!1;if(null!=t){const e=t.toLowerCase();if(["application/json","application/problem+json","application/xml","application/xhtml+xml","application/javascript","application/ecmascript","application/x-www-form-urlencoded","text/"].some(t=>e.includes(t))||e.includes("charset="))return!0}return e.reduce((t,e)=>9===e||10===e||13===e||e>=32&&e<=126?t+1:t,0)/e.length>.8}formatBinaryPreview(t,e){return`0x${t.map(t=>t.toString(16).padStart(2,"0")).join("")}${e?"…":""}`}deserializeRequestPayload(t){const e=new ne(t),i=Zt(e.read(32)),r=e.readVarIntNum();let s="GET";r>0&&(s=Yt(e.read(r)));const n=e.readVarIntNum();let a="";n>0&&(a=Yt(e.read(n)));const o=e.readVarIntNum();let c="";o>0&&(c=Yt(e.read(o)));const h={},u=e.readVarIntNum();if(u>0)for(let t=0;t<u;t++){const t=e.readVarIntNum(),i=e.read(t),r=Yt(i),s=e.readVarIntNum(),n=e.read(s),a=Yt(n);h[r]=a}let d;const l=e.readVarIntNum();return l>0&&(d=e.read(l)),{urlPostfix:a+c,method:s,headers:h,body:d,requestId:i}}}class os{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(t,e,i,r){this.wallet=t,this.requestedCertificates=e,this.sessionManager=i??new Jr,this.originator=r}async fetch(t,e={}){if("number"==typeof e.retryCounter){if(e.retryCounter<=0)throw new Error("Request failed after maximum number of retries.");e.retryCounter--}const i=await new Promise(async(i,r)=>{try{const{method:s="GET",headers:n={},body:a}=e,o=new URL(t),c=o.origin;let h;if(void 0===this.peers[c]){const t=new as(c);h={peer:new ss(this.wallet,t,this.requestedCertificates,this.sessionManager,void 0,this.originator),pendingCertificateRequests:[]},this.peers[c]=h,this.peers[c].peer.listenForCertificatesReceived((t,e)=>{this.certificatesReceived.push(...e)}),this.peers[c].peer.listenForCertificatesRequested(async(t,e)=>{try{this.peers[c].pendingCertificateRequests.push(!0);const i=await ts(this.wallet,e,t,this.originator);await this.peers[c].peer.sendCertificateResponse(t,i)}finally{await new Promise(t=>setTimeout(t,500)),this.peers[c].pendingCertificateRequests.shift()}})}else{if(!1===this.peers[c].supportsMutualAuth){try{const r=await this.handleFetchAndValidate(t,e,this.peers[c]);i(r)}catch(t){r(t)}return}h=this.peers[c]}const u=We(32),d=Zt(u),l=await this.serializeRequest(s,n,a,o,u);this.callbacks[d]={resolve:i,reject:r};const f=h.peer.listenForGeneralMessages((t,e)=>{const i=new ne(e);if(Zt(i.read(32))!==d)return;h.peer.stopListeningForGeneralMessages(f),this.peers[c].identityKey=t,this.peers[c].supportsMutualAuth=!0;const r=i.readVarIntNum(),s={},n=i.readVarIntNum();if(n>0)for(let t=0;t<n;t++){const t=i.readVarIntNum(),e=i.read(t),r=Yt(e),n=i.readVarIntNum(),a=i.read(n),o=Yt(a);s[r]=o}let a;s["x-bsv-auth-identity-key"]=t;const o=i.readVarIntNum();o>0&&(a=i.read(o));const u=new Response(a?new Uint8Array(a):null,{status:r,statusText:`${r}`,headers:new Headers(s)});this.callbacks[d].resolve(u),delete this.callbacks[d]});if(h.pendingCertificateRequests.length>0){const t=3e4,e=100;await new Promise((i,r)=>{const s=Date.now(),n=()=>{0!==h.pendingCertificateRequests.length?Date.now()-s>t?r(new Error("Timeout waiting for certificate request to complete")):setTimeout(n,e):i()};n()})}await h.peer.toPeer(l.toArray(),h.identityKey).catch(async s=>{if(s.message.includes("Session not found for nonce")){delete this.peers[c],e.retryCounter??=3;const r=await this.fetch(t,e);return void i(r)}if(s.message.includes("HTTP server failed to authenticate"))try{const r=await this.handleFetchAndValidate(t,e,h);return void i(r)}catch(t){r(t)}else r(s)})}catch(t){r(t)}});return 402===i.status?await this.handlePaymentAndRetry(t,e,i):i}async sendCertificateRequest(t,e){const i=new URL(t).origin;let r;if(void 0!==this.peers[i])r={peer:this.peers[i].peer};else{const t=new as(i);r={peer:new ss(this.wallet,t,this.requestedCertificates,this.sessionManager,this.originator)},this.peers[i]=r}return await new Promise(async(t,i)=>{const s=r.peer.listenForCertificatesReceived((e,i)=>{r.peer.stopListeningForCertificatesReceived(s),this.certificatesReceived.push(...i),t(i)});try{await r.peer.requestCertificates(e,r.identityKey)}catch(t){r.peer.stopListeningForCertificatesReceived(s),i(t)}})}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(t,e,i,r,s){const n=new se;if(n.write(s),n.writeVarIntNum(t.length),n.write(Wt(t)),r.pathname.length>0){const t=Wt(r.pathname);n.writeVarIntNum(t.length),n.write(t)}else n.writeVarIntNum(-1);if(r.search.length>0){const t=Wt(r.search);n.writeVarIntNum(t.length),n.write(t)}else n.writeVarIntNum(-1);const a=[];for(let[t,i]of Object.entries(e))if(t=t.toLowerCase(),t.startsWith("x-bsv-")||"authorization"===t){if(t.startsWith("x-bsv-auth"))throw new Error("No BSV auth headers allowed here!");a.push([t,i])}else{if(!t.startsWith("content-type"))throw new Error("Unsupported header in the simplified fetch implementation. Only content-type, authorization, and x-bsv-* headers are supported.");i=i.split(";")[0].trim(),a.push([t,i])}a.sort(([t],[e])=>t.localeCompare(e)),n.writeVarIntNum(a.length);for(let t=0;t<a.length;t++){const e=Wt(a[t][0],"utf8");n.writeVarIntNum(e.length),n.write(e);const i=Wt(a[t][1],"utf8");n.writeVarIntNum(i.length),n.write(i)}if(["POST","PUT","PATCH","DELETE"].includes(t.toUpperCase())&&void 0===i){const t=a.find(([t])=>"content-type"===t);i=t&&t[1].includes("application/json")?"{}":""}if(i){const t=await this.normalizeBodyToNumberArray(i);n.writeVarIntNum(t.length),n.write(t)}else n.writeVarIntNum(-1);return n}async handleFetchAndValidate(t,e,i){const r=await fetch(t,e);if(r.headers.forEach(t=>{if(t.toLocaleLowerCase().startsWith("x-bsv"))throw new Error("The server is trying to claim it has been authenticated when it has not!")}),r.ok)return i.supportsMutualAuth=!1,r;throw new Error(`Request failed with status: ${r.status}`)}async handlePaymentAndRetry(t,e={},i){const r=i.headers.get("x-bsv-payment-version");if(!r||"1.0"!==r)throw new Error(`Unsupported x-bsv-payment-version response header. Client version: 1.0, Server version: ${r}`);const s=i.headers.get("x-bsv-payment-satoshis-required");if(!s)throw new Error("Missing x-bsv-payment-satoshis-required response header.");const n=parseInt(s);if(isNaN(n)||n<=0)throw new Error("Invalid x-bsv-payment-satoshis-required response header value.");const a=i.headers.get("x-bsv-auth-identity-key");if("string"!=typeof a)throw new Error("Missing x-bsv-auth-identity-key response header.");const o=i.headers.get("x-bsv-payment-derivation-prefix");if("string"!=typeof o||o.length<1)throw new Error("Missing x-bsv-payment-derivation-prefix response header.");let c=e.paymentContext;if(null!=c?!this.isPaymentContextCompatible(c,n,a,o)&&(this.logPaymentAttempt("warn","Server adjusted payment requirements; regenerating transaction",this.composePaymentLogDetails(t,c)),c=await this.createPaymentContext(t,e,n,a,o)):c=await this.createPaymentContext(t,e,n,a,o),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(t,c,new Error("Maximum payment attempts exceeded before retrying"));const h={...e.headers??{}};h["x-bsv-payment"]=JSON.stringify({derivationPrefix:c.derivationPrefix,derivationSuffix:c.derivationSuffix,transaction:c.transactionBase64});const u={...e,headers:h,paymentContext:c};"number"!=typeof u.retryCounter&&(u.retryCounter=3);const d=c.attempts+1,l=c.maxAttempts;c.attempts=d;const f=this.composePaymentLogDetails(t,c);this.logPaymentAttempt("warn",`Attempting paid request (${d}/${l})`,f);try{const e=await this.fetch(t,u);return this.logPaymentAttempt("info",`Paid request attempt ${d} succeeded`,f),e}catch(e){const r=this.createPaymentErrorEntry(c.attempts,e);if(c.errors.push(r),this.logPaymentAttempt("error",`Paid request attempt ${d} failed`,{...f,error:{message:r.message,stack:r.stack}}),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(t,c,e);const s=this.getPaymentRetryDelay(c.attempts);return await this.wait(s),this.handlePaymentAndRetry(t,u,i)}}isPaymentContextCompatible(t,e,i,r){return t.satoshisRequired===e&&t.serverIdentityKey===i&&t.derivationPrefix===r}async createPaymentContext(t,e,i,r,s){const n=await Qr(this.wallet,void 0,this.originator),{publicKey:a}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${s} ${n}`,counterparty:r},this.originator),o=(new Fi).lock($e.fromString(a).toAddress()).toHex(),{tx:c}=await this.wallet.createAction({description:`Payment for request to ${new URL(t).origin}`,outputs:[{satoshis:i,lockingScript:o,customInstructions:JSON.stringify({derivationPrefix:s,derivationSuffix:n,payee:r}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}},this.originator),{publicKey:h}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return{satoshisRequired:i,transactionBase64:Zt(c),derivationPrefix:s,derivationSuffix:n,serverIdentityKey:r,clientIdentityKey:h,attempts:0,maxAttempts:this.getMaxPaymentAttempts(e),errors:[],requestSummary:this.buildPaymentRequestSummary(t,e)}}getMaxPaymentAttempts(t){const e="number"==typeof t.paymentRetryAttempts?t.paymentRetryAttempts:void 0;return"number"==typeof e&&e>0?Math.floor(e):3}buildPaymentRequestSummary(t,e){const i={...e.headers??{}},r="string"==typeof e.method?e.method.toUpperCase():"GET",s=this.describeRequestBodyForLogging(e.body);return{url:t,method:r,headers:i,bodyType:s.type,bodyByteLength:s.byteLength}}describeRequestBodyForLogging(t){if(null==t)return{type:"none",byteLength:0};if("string"==typeof t)return{type:"string",byteLength:Wt(t,"utf8").length};if(Array.isArray(t))return t.every(t=>"number"==typeof t)?{type:"number[]",byteLength:t.length}:{type:"array",byteLength:t.length};if("undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer)return{type:"ArrayBuffer",byteLength:t.byteLength};if("undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(t))return{type:null!=t.constructor?t.constructor.name:"TypedArray",byteLength:t.byteLength};if("undefined"!=typeof Blob&&t instanceof Blob)return{type:"Blob",byteLength:t.size};if("undefined"!=typeof FormData&&t instanceof FormData)return{type:"FormData",byteLength:0};if("undefined"!=typeof URLSearchParams&&t instanceof URLSearchParams){const e=t.toString();return{type:"URLSearchParams",byteLength:Wt(e,"utf8").length}}if("undefined"!=typeof ReadableStream&&t instanceof ReadableStream)return{type:"ReadableStream",byteLength:0};try{const e=JSON.stringify(t);if("string"==typeof e)return{type:"object",byteLength:Wt(e,"utf8").length}}catch(t){}return{type:typeof t,byteLength:0}}composePaymentLogDetails(t,e){return{url:t,request:e.requestSummary,payment:{satoshis:e.satoshisRequired,transactionBase64:e.transactionBase64,derivationPrefix:e.derivationPrefix,derivationSuffix:e.derivationSuffix,serverIdentityKey:e.serverIdentityKey,clientIdentityKey:e.clientIdentityKey},attempts:{used:e.attempts,max:e.maxAttempts},errors:e.errors}}logPaymentAttempt(t,e,i){const r="[AuthFetch][Payment]";"error"===t?console.error(`${r} ${e}`,i):"warn"===t?console.warn(`${r} ${e}`,i):"function"==typeof console.info?console.info(`${r} ${e}`,i):console.log(`${r} ${e}`,i)}createPaymentErrorEntry(t,e){const i={attempt:t,timestamp:(new Date).toISOString(),message:"",stack:void 0};return e instanceof Error?(i.message=e.message,i.stack=e.stack??void 0):i.message=String(e),i}getPaymentRetryDelay(t){return 250*Math.min(t,5)}async wait(t){t<=0||await new Promise(e=>setTimeout(e,t))}buildPaymentFailureError(t,e,i){const r=`Paid request to ${t} failed after ${e.attempts}/${e.maxAttempts} attempts. Sent ${e.satoshisRequired} satoshis to ${e.serverIdentityKey}.`,s=new Error(r),n={request:e.requestSummary,payment:{satoshis:e.satoshisRequired,transactionBase64:e.transactionBase64,derivationPrefix:e.derivationPrefix,derivationSuffix:e.derivationSuffix,serverIdentityKey:e.serverIdentityKey,clientIdentityKey:e.clientIdentityKey},attempts:{used:e.attempts,max:e.maxAttempts},errors:e.errors};return s.details=n,i instanceof Error&&(s.cause=i),s}async normalizeBodyToNumberArray(t){if(null==t)return[];if("object"==typeof t)return Wt(JSON.stringify(t,"utf8"));if(Array.isArray(t)&&t.every(t=>"number"==typeof t))return t;if("string"==typeof t)return Wt(t,"utf8");if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)){const e=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer);return Array.from(e)}if(t instanceof Blob){const e=await t.arrayBuffer();return Array.from(new Uint8Array(e))}if(t instanceof FormData){const e=[];t.forEach((t,i)=>{e.push([i,t.toString()])});const i=new URLSearchParams(e).toString();return Wt(i,"utf8")}if(t instanceof URLSearchParams)return Wt(t.toString(),"utf8");if(t instanceof ReadableStream)throw new Error("ReadableStream cannot be directly converted to number[].");throw new Error("Unsupported body type in this SimplifiedFetch implementation.")}}class cs{pushDrop;static decode(t){const e=Di.decode(t);if(e.fields.length<4)throw new Error("Invalid SHIP/SLAP advertisement!");const i=Yt(e.fields[0]);if("SHIP"!==i&&"SLAP"!==i)throw new Error("Invalid protocol type!");return{protocol:i,identityKey:jt(e.fields[1]),domain:Yt(e.fields[2]),topicOrService:Yt(e.fields[3])}}constructor(t,e){this.pushDrop=new Di(t,e)}async lock(t,e,i){const{publicKey:r}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([Wt(t,"utf8"),Wt(r,"hex"),Wt(e,"utf8"),Wt(i,"utf8")],[2,"SHIP"===t?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}unlock(t){return this.pushDrop.unlock([2,"SHIP"===t?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}}const hs="bsvsdk_overlay_host_reputation_v1";class us{stats;store;constructor(t){this.stats=new Map,this.store=t??this.getLocalStorageAdapter(),this.loadFromStorage()}reset(){this.stats.clear()}recordSuccess(t,e){const i=this.getOrCreate(t),r=Date.now(),s=Number.isFinite(e)&&e>=0?e:1500;null===i.avgLatencyMs?i.avgLatencyMs=s:i.avgLatencyMs=.75*i.avgLatencyMs+.25*s,i.lastLatencyMs=s,i.totalSuccesses+=1,i.consecutiveFailures=0,i.backoffUntil=0,i.lastUpdatedAt=r,i.lastError=void 0,this.saveToStorage()}recordFailure(t,e){const i=this.getOrCreate(t),r=Date.now();i.totalFailures+=1,i.consecutiveFailures+=1;const s="string"==typeof e?e:e instanceof Error?e.message:void 0;"string"==typeof s&&(s.includes("ERR_NAME_NOT_RESOLVED")||s.includes("ENOTFOUND")||s.includes("getaddrinfo")||s.includes("Failed to fetch"))&&i.consecutiveFailures<3&&(i.consecutiveFailures=3);const n=Math.max(i.consecutiveFailures-2,0);if(0===n)i.backoffUntil=0;else{const t=Math.min(6e4,1e3*Math.pow(2,n-1));i.backoffUntil=r+t}i.lastUpdatedAt=r,i.lastError="string"==typeof e?e:e instanceof Error?e.message:void 0,this.saveToStorage()}rankHosts(t,e=Date.now()){const i=new Map;t.forEach((t,e)=>{"string"==typeof t&&0!==t.length&&(i.has(t)||i.set(t,e))});const r=Array.from(i.keys()).map(t=>{const r=this.getOrCreate(t);return{...r,score:this.computeScore(r,e),originalOrder:i.get(t)??0}});return r.sort((t,i)=>{const r=t.backoffUntil>e;return r!==i.backoffUntil>e?r?1:-1:t.score!==i.score?t.score-i.score:t.totalSuccesses!==i.totalSuccesses?i.totalSuccesses-t.totalSuccesses:t.originalOrder-i.originalOrder}),r.map(({originalOrder:t,...e})=>e)}snapshot(t){const e=this.stats.get(t);return null!=e?{...e}:void 0}getStorage(){try{const t="object"==typeof globalThis?globalThis:void 0;if(null==t||null==t.localStorage)return;return t.localStorage}catch{return}}getLocalStorageAdapter(){const t=this.getStorage();if(null!=t)return{get:e=>{try{return t.getItem(e)}catch{return null}},set:(e,i)=>{try{t.setItem(e,i)}catch{}}}}loadFromStorage(){const t=this.store;if(null!=t)try{const e=t.get(hs);if("string"!=typeof e||0===e.length)return;const i=JSON.parse(e);if("object"!=typeof i||null===i)return;this.stats.clear();for(const t of Object.keys(i)){const e=i[t];if(null!=e&&"object"==typeof e){const i={host:String(e.host??t),totalSuccesses:Number(e.totalSuccesses??0),totalFailures:Number(e.totalFailures??0),consecutiveFailures:Number(e.consecutiveFailures??0),avgLatencyMs:null==e.avgLatencyMs?null:Number(e.avgLatencyMs),lastLatencyMs:null==e.lastLatencyMs?null:Number(e.lastLatencyMs),backoffUntil:Number(e.backoffUntil??0),lastUpdatedAt:Number(e.lastUpdatedAt??0),lastError:"string"==typeof e.lastError?e.lastError:void 0};this.stats.set(i.host,i)}}}catch{}}saveToStorage(){const t=this.store;if(null!=t)try{const e={};for(const[t,i]of this.stats.entries())e[t]=i;t.set(hs,JSON.stringify(e))}catch{}}computeScore(t,e){const i=t.avgLatencyMs??1500,r=400*t.consecutiveFailures,s=Math.min(30*t.totalSuccesses,i/2);return i+r+(t.backoffUntil>e?t.backoffUntil-e:0)-s}getOrCreate(t){let e=this.stats.get(t);return null==e&&(e={host:t,totalSuccesses:0,totalFailures:0,consecutiveFailures:0,avgLatencyMs:null,lastLatencyMs:null,backoffUntil:0,lastUpdatedAt:0},this.stats.set(t,e)),e}}const ds=new us,ls="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch,fs=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],ps=["https://testnet-users.bapp.dev"];class gs{fetchClient;allowHTTP;constructor(t=ls,e=!1){if("function"!=typeof t)throw new Error("HTTPSOverlayLookupFacilitator requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=t,this.allowHTTP=e}async lookup(t,e,i=5e3){if(!t.startsWith("https:")&&!this.allowHTTP)throw new Error('HTTPS facilitator can only use URLs that start with "https:"');const r="undefined"!=typeof AbortController?new AbortController:void 0,s=setTimeout(()=>{try{r?.abort()}catch{}},i);try{const i={method:"POST",headers:{"Content-Type":"application/json","X-Aggregation":"yes"},body:JSON.stringify({service:e.service,query:e.query}),signal:r?.signal},s=await this.fetchClient(`${t}/lookup`,i);if(!s.ok)throw new Error(`Failed to facilitate lookup (HTTP ${s.status})`);if("application/octet-stream"===s.headers.get("content-type")){const t=await s.arrayBuffer(),e=new ne([...new Uint8Array(t)]),i=e.readVarIntNum(),r=[];for(let t=0;t<i;t++){const t=jt(e.read(32)),i=e.readVarIntNum(),s=e.readVarIntNum();let n;s>0&&(n=e.read(s)),r.push({txid:t,outputIndex:i,context:n})}const n=e.read();return{type:"output-list",outputs:r.map(t=>({outputIndex:t.outputIndex,context:t.context,beef:ir.fromBEEF(n,t.txid).toBEEF()}))}}return await s.json()}catch(t){if("AbortError"===t?.name)throw new Error("Request timed out");throw t}finally{clearTimeout(s)}}}class ys{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostReputation;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(t={}){this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new gs(void 0,"local"===this.networkPreset),this.slapTrackers=t.slapTrackers??("mainnet"===this.networkPreset?fs:ps);const e=t.hostOverrides??{};this.assertValidOverrideServices(e),this.hostOverrides=e,this.additionalHosts=t.additionalHosts??{};const i=t.reputationStorage;"localStorage"===i?this.hostReputation=new us:"object"==typeof i&&null!==i&&"function"==typeof i.get&&"function"==typeof i.set?this.hostReputation=new us(i):this.hostReputation=ds,this.hostsTtlMs=t.cache?.hostsTtlMs??3e5,this.hostsMaxEntries=t.cache?.hostsMaxEntries??128,this.txMemoTtlMs=t.cache?.txMemoTtlMs??6e5,this.hostsCache=new Map,this.hostsInFlight=new Map,this.txMemo=new Map}async query(t,e){let i=[];if(i="ls_slap"===t.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[t.service]?this.hostOverrides[t.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.getCompetentHostsCached(t.service),this.additionalHosts[t.service]?.length>0){const e=this.additionalHosts[t.service],r=new Set(i);for(const t of e)r.has(t)||i.push(t)}if(i.length<1)throw new Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${t.service}`);const r=this.prepareHostsForQuery(i,`lookup service ${t.service}`);if(r.length<1)throw new Error(`All competent hosts for ${t.service} are temporarily unavailable due to backoff.`);const s=await new Promise(i=>{const s=[];let n=r.length,a=null;const o=()=>{null!==a&&clearTimeout(a),i(s)};for(const i of r)this.lookupHostWithTracking(i,t,e).then(t=>{"output-list"===t?.type&&Array.isArray(t.outputs)&&t.outputs.length>0&&(s.push(t),1===s.length&&n>1&&(a=setTimeout(o,200)))}).catch(()=>{}).finally(()=>{n--,0===n&&o()})}),n=new Map,a=t=>"object"!=typeof t?"":t.join(",");for(const t of s)for(const e of t.outputs){const t=a(e.beef);let i=this.txMemo.get(t);const r=Date.now();if("object"!=typeof i||null===i||i.expiresAt<=r)try{i={txId:ir.fromBEEF(e.beef).id("hex"),expiresAt:r+this.txMemoTtlMs},this.txMemo.size>4096&&this.evictOldest(this.txMemo),this.txMemo.set(t,i)}catch{continue}const s=`${i.txId}.${e.outputIndex}`;n.set(s,e)}return{type:"output-list",outputs:Array.from(n.values())}}async getCompetentHostsCached(t){const e=Date.now(),i=this.hostsCache.get(t);if("object"==typeof i&&i.expiresAt>e)return i.hosts.slice();if("object"==typeof i&&i.expiresAt<=e)return this.hostsInFlight.has(t)||this.hostsInFlight.set(t,this.refreshHosts(t).finally(()=>{this.hostsInFlight.delete(t)})),i.hosts.slice();if(this.hostsInFlight.has(t))try{const e=await this.hostsInFlight.get(t);if("object"!=typeof e)throw new Error("Hosts is not defined.");return e.slice()}catch{}const r=this.refreshHosts(t).finally(()=>{this.hostsInFlight.delete(t)});return this.hostsInFlight.set(t,r),(await r).slice()}async refreshHosts(t){const e=await this.findCompetentHosts(t),i=Date.now()+this.hostsTtlMs;if(!this.hostsCache.has(t)&&this.hostsCache.size>=this.hostsMaxEntries){const t=this.hostsCache.keys().next().value;void 0!==t&&this.hostsCache.delete(t)}return this.hostsCache.set(t,{hosts:e,expiresAt:i}),e}extractHostsFromAnswer(t,e){const i=[];if("output-list"!==t.type)return i;for(const r of t.outputs)try{const t=ir.fromBEEF(r.beef),s=t.outputs[r.outputIndex]?.lockingScript;if("object"!=typeof s||null===s)continue;const n=cs.decode(s);if(n.topicOrService!==e||"SLAP"!==n.protocol)continue;"string"==typeof n.domain&&n.domain.length>0&&i.push(n.domain)}catch{continue}return i}async findCompetentHosts(t){const e={service:"ls_slap",query:{service:t}},i=this.prepareHostsForQuery(this.slapTrackers,"SLAP trackers");return 0===i.length?[]:await new Promise(r=>{const s=new Set;let n=!1,a=i.length;for(const o of i)this.lookupHostWithTracking(o,e,5e3).then(e=>{const i=this.extractHostsFromAnswer(e,t);for(const t of i)s.add(t);!n&&s.size>0&&(n=!0,r([...s]))}).catch(()=>{}).finally(()=>{a--,0!==a||n||(n=!0,r([...s]))})})}evictOldest(t){const e=t.keys().next().value;void 0!==e&&t.delete(e)}assertValidOverrideServices(t){for(const e of Object.keys(t))if(!e.startsWith("ls_"))throw new Error(`Host override service names must start with "ls_": ${e}`)}prepareHostsForQuery(t,e){if(0===t.length)return[];const i=Date.now(),r=this.hostReputation.rankHosts(t,i),s=r.filter(t=>t.backoffUntil<=i).map(t=>t.host);if(s.length>0)return s;const n=Math.min(...r.map(t=>t.backoffUntil)),a=Math.max(n-i,0);throw new Error(`All ${e} hosts are backing off for approximately ${a}ms due to repeated failures.`)}async lookupHostWithTracking(t,e,i){const r=Date.now();try{const s=await this.facilitator.lookup(t,e,i),n=Date.now()-r;return"object"==typeof s&&null!==s&&"output-list"===s.type&&Array.isArray(s.outputs)?this.hostReputation.recordSuccess(t,n):this.hostReputation.recordFailure(t,"Invalid lookup response"),s}catch(e){throw this.hostReputation.recordFailure(t,e),e}}}class bs{httpClient;allowHTTP;constructor(t=fetch,e=!1){this.httpClient=t,this.allowHTTP=e}async send(t,e){if(!t.startsWith("https:")&&!this.allowHTTP)throw new Error('HTTPS facilitator can only use URLs that start with "https:"');const i={"Content-Type":"application/octet-stream","X-Topics":JSON.stringify(e.topics)};let r;if(Array.isArray(e.offChainValues)){i["x-includes-off-chain-values"]="true";const t=new se;t.writeVarIntNum(e.beef.length),t.write(e.beef),t.write(e.offChainValues),r=new Uint8Array(t.toArray())}else r=new Uint8Array(e.beef);const s=await fetch(`${t}/submit`,{method:"POST",headers:i,body:r});if(s.ok)return await s.json();throw new Error("Failed to facilitate broadcast")}}class ms{topics;facilitator;resolver;requireAcknowledgmentFromAllHostsForTopics;requireAcknowledgmentFromAnyHostForTopics;requireAcknowledgmentFromSpecificHostsForTopics;networkPreset;interestedHostsCache=null;interestedHostsInFlight=null;interestedHostsTtlMs;constructor(t,e={}){if(0===t.length)throw new Error("At least one topic is required for broadcast.");if(t.some(t=>!t.startsWith("tm_")))throw new Error('Every topic must start with "tm_".');this.topics=t,this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new bs(void 0,"local"===this.networkPreset),this.resolver=e.resolver??new ys({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=e.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=e.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=e.requireAcknowledgmentFromSpecificHostsForTopics??{},this.interestedHostsTtlMs=3e5}async broadcast(t){let e;const i=t.metadata.get("OffChainValues");try{e=t.toBEEF()}catch(t){throw new Error("Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.")}const r=await this.findInterestedHosts();if(0===Object.keys(r).length)return{status:"error",code:"ERR_NO_HOSTS_INTERESTED",description:`No ${this.networkPreset} hosts are interested in receiving this transaction.`};const s=Object.entries(r).map(async([t,r])=>{try{const s=await this.facilitator.send(t,{beef:e,offChainValues:i,topics:[...r]});if(null==s||0===Object.keys(s).length)throw new Error("Steak has no topics.");return{host:t,success:!0,steak:s}}catch(e){return console.error(e),{host:t,success:!1,error:e}}}),n=(await Promise.all(s)).filter(t=>t.success);if(0===n.length)return{status:"error",code:"ERR_ALL_HOSTS_REJECTED",description:`All ${this.networkPreset} topical hosts have rejected the transaction.`};const a={};for(const t of n){const e=t.host,i=t.steak,r=new Set;for(const[t,e]of Object.entries(i)){const i=e.outputsToAdmit,s=e.coinsToRetain,n=e.coinsRemoved;(i?.length>0||s?.length>0||n?.length>0)&&r.add(t)}a[e]=r}let o,c,h,u;return"all"===this.requireAcknowledgmentFromAllHostsForTopics?(o=this.topics,c="all"):"any"===this.requireAcknowledgmentFromAllHostsForTopics?(o=this.topics,c="any"):Array.isArray(this.requireAcknowledgmentFromAllHostsForTopics)?(o=this.requireAcknowledgmentFromAllHostsForTopics,c="all"):(o=this.topics,c="all"),o.length>0&&!this.checkAcknowledgmentFromAllHosts(a,o,c)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED",description:"Not all hosts acknowledged the required topics."}:("all"===this.requireAcknowledgmentFromAnyHostForTopics?(h=this.topics,u="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(h=this.topics,u="any"):Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?(h=this.requireAcknowledgmentFromAnyHostForTopics,u="all"):(h=[],u="all"),h.length>0&&!this.checkAcknowledgmentFromAnyHost(a,h,u)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ANY_HOST_FAILED",description:"No host acknowledged the required topics."}:Object.keys(this.requireAcknowledgmentFromSpecificHostsForTopics).length>0&&!this.checkAcknowledgmentFromSpecificHosts(a,this.requireAcknowledgmentFromSpecificHostsForTopics)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_SPECIFIC_HOSTS_FAILED",description:"Specific hosts did not acknowledge the required topics."}:{status:"success",txid:t.id("hex"),message:`Sent to ${n.length} Overlay Services ${1===n.length?"host":"hosts"}.`})}checkAcknowledgmentFromAllHosts(t,e,i){for(const r of Object.values(t))if("all"===i){for(const t of e)if(!r.has(t))return!1}else if("any"===i){let t=!1;for(const i of e)if(r.has(i)){t=!0;break}if(!t)return!1}return!0}checkAcknowledgmentFromAnyHost(t,e,i){if("all"===i){for(const i of Object.values(t)){let t=!0;for(const r of e)if(!i.has(r)){t=!1;break}if(t)return!0}return!1}for(const i of Object.values(t))for(const t of e)if(i.has(t))return!0;return!1}checkAcknowledgmentFromSpecificHosts(t,e){for(const[i,r]of Object.entries(e)){const e=t[i];if(null==e)return!1;let s,n;if("all"===r||"any"===r)n=r,s=this.topics;else{if(!Array.isArray(r))continue;s=r,n="all"}if("all"===n){for(const t of s)if(!e.has(t))return!1}else if("any"===n){let t=!1;for(const i of s)if(e.has(i)){t=!0;break}if(!t)return!1}}return!0}async findInterestedHosts(){if("local"===this.networkPreset){const t=new Set;for(let e=0;e<this.topics.length;e++)t.add(this.topics[e]);return{"http://localhost:8080":t}}const t=Date.now();if(null!=this.interestedHostsCache&&this.interestedHostsCache.expiresAt>t)return this.interestedHostsCache.hosts;if(null!=this.interestedHostsInFlight)return await this.interestedHostsInFlight;this.interestedHostsInFlight=this.fetchInterestedHosts();try{const t=await this.interestedHostsInFlight;return this.interestedHostsCache={hosts:t,expiresAt:Date.now()+this.interestedHostsTtlMs},t}finally{this.interestedHostsInFlight=null}}async fetchInterestedHosts(){const t={},e=await this.resolver.query({service:"ls_ship",query:{topics:this.topics}},5e3);if("output-list"!==e.type)throw new Error("SHIP answer is not an output list.");for(const i of e.outputs)try{const e=ir.fromBEEF(i.beef).outputs[i.outputIndex].lockingScript,r=cs.decode(e);if(!this.topics.includes(r.topicOrService)||"SHIP"!==r.protocol)continue;void 0===t[r.domain]&&(t[r.domain]=new Set),t[r.domain].add(r.topicOrService)}catch(t){continue}return t}}const ws=Object.create(null);ws.open="0",ws.close="1",ws.ping="2",ws.pong="3",ws.message="4",ws.upgrade="5",ws.noop="6";const vs=Object.create(null);Object.keys(ws).forEach(t=>{vs[ws[t]]=t});const Is={type:"error",data:"parser error"},ks="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Ss="function"==typeof ArrayBuffer,Es=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,xs=({type:t,data:e},i,r)=>ks&&e instanceof Blob?i?r(e):_s(e,r):Ss&&(e instanceof ArrayBuffer||Es(e))?i?r(e):_s(new Blob([e]),r):r(ws[t]+(e||"")),_s=(t,e)=>{const i=new FileReader;return i.onload=function(){const t=i.result.split(",")[1];e("b"+(t||""))},i.readAsDataURL(t)};function Ps(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let As;const Ns="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)Ns["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const Os="function"==typeof ArrayBuffer,Ts=(t,e)=>{if("string"!=typeof t)return{type:"message",data:Rs(t,e)};const i=t.charAt(0);return"b"===i?{type:"message",data:Cs(t.substring(1),e)}:vs[i]?t.length>1?{type:vs[i],data:t.substring(1)}:{type:vs[i]}:Is},Cs=(t,e)=>{if(Os){const i=(t=>{let e,i,r,s,n,a=.75*t.length,o=t.length,c=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);const h=new ArrayBuffer(a),u=new Uint8Array(h);for(e=0;e<o;e+=4)i=Ns[t.charCodeAt(e)],r=Ns[t.charCodeAt(e+1)],s=Ns[t.charCodeAt(e+2)],n=Ns[t.charCodeAt(e+3)],u[c++]=i<<2|r>>4,u[c++]=(15&r)<<4|s>>2,u[c++]=(3&s)<<6|63&n;return h})(t);return Rs(i,e)}return{base64:!0,data:t}},Rs=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,Bs=String.fromCharCode(30);let Ls;function Ms(t){return t.reduce((t,e)=>t+e.length,0)}function Fs(t,e){if(t[0].length===e)return t.shift();const i=new Uint8Array(e);let r=0;for(let s=0;s<e;s++)i[s]=t[0][r++],r===t[0].length&&(t.shift(),r=0);return t.length&&r<t[0].length&&(t[0]=t[0].slice(r)),i}function Us(t){if(t)return function(t){for(var e in Us.prototype)t[e]=Us.prototype[e];return t}(t)}Us.prototype.on=Us.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Us.prototype.once=function(t,e){function i(){this.off(t,i),e.apply(this,arguments)}return i.fn=e,this.on(t,i),this},Us.prototype.off=Us.prototype.removeListener=Us.prototype.removeAllListeners=Us.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var i,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var s=0;s<r.length;s++)if((i=r[s])===e||i.fn===e){r.splice(s,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},Us.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),i=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(i){r=0;for(var s=(i=i.slice(0)).length;r<s;++r)i[r].apply(this,e)}return this},Us.prototype.emitReserved=Us.prototype.emit,Us.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Us.prototype.hasListeners=function(t){return!!this.listeners(t).length};const Ds="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),Hs="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function qs(t,...e){return e.reduce((e,i)=>(t.hasOwnProperty(i)&&(e[i]=t[i]),e),{})}const Vs=Hs.setTimeout,Ks=Hs.clearTimeout;function $s(t,e){e.useNativeTimers?(t.setTimeoutFn=Vs.bind(Hs),t.clearTimeoutFn=Ks.bind(Hs)):(t.setTimeoutFn=Hs.setTimeout.bind(Hs),t.clearTimeoutFn=Hs.clearTimeout.bind(Hs))}function js(t){return"string"==typeof t?function(t){let e=0,i=0;for(let r=0,s=t.length;r<s;r++)e=t.charCodeAt(r),e<128?i+=1:e<2048?i+=2:e<55296||e>=57344?i+=3:(r++,i+=4);return i}(t):Math.ceil(1.33*(t.byteLength||t.size))}function zs(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Ws extends Error{constructor(t,e,i){super(t),this.description=e,this.context=i,this.type="TransportError"}}class Gs extends Us{constructor(t){super(),this.writable=!1,$s(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,i){return super.emitReserved("error",new Ws(t,e,i)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=Ts(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=function(t){let e="";for(let i in t)t.hasOwnProperty(i)&&(e.length&&(e+="&"),e+=encodeURIComponent(i)+"="+encodeURIComponent(t[i]));return e}(t);return e.length?"?"+e:""}}class Xs extends Gs{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const i=t.split(Bs),r=[];for(let t=0;t<i.length;t++){const s=Ts(i[t],e);if(r.push(s),"error"===s.type)break}return r})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const i=t.length,r=new Array(i);let s=0;t.forEach((t,n)=>{xs(t,!1,t=>{r[n]=t,++s===i&&e(r.join(Bs))})})})(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=zs()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let Ys=!1;try{Ys="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const Js=Ys;function Zs(){}class Qs extends Xs{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let i=location.port;i||(i=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||i!==t.port}}doWrite(t,e){const i=this.request({method:"POST",data:t});i.on("success",e),i.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class tn extends Us{constructor(t,e,i){super(),this.createRequest=t,$s(this,i),this._opts=i,this._method=i.method||"GET",this._uri=e,this._data=void 0!==i.data?i.data:null,this._create()}_create(){var t;const e=qs(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const i=this._xhr=this.createRequest(e);try{i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&i.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{i.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var t;3===i.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(i.getResponseHeader("set-cookie"))),4===i.readyState&&(200===i.status||1223===i.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof i.status?i.status:0)},0))},i.send(this._data)}catch(t){return void this.setTimeoutFn(()=>{this._onError(t)},0)}"undefined"!=typeof document&&(this._index=tn.requestsCount++,tn.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=Zs,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete tn.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}function en(){for(let t in tn.requests)tn.requests.hasOwnProperty(t)&&tn.requests[t].abort()}tn.requestsCount=0,tn.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",en):"function"==typeof addEventListener&&addEventListener("onpagehide"in Hs?"pagehide":"unload",en,!1));const rn=function(){const t=sn({xdomain:!1});return t&&null!==t.responseType}();function sn(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||Js))return new XMLHttpRequest}catch(t){}if(!e)try{return new(Hs[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const nn="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class an extends Gs{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,i=nn?{}:qs(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,i)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const i=t[e],r=e===t.length-1;xs(i,this.supportsBinary,t=>{try{this.doWrite(i,t)}catch(t){}r&&Ds(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=zs()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const on=Hs.WebSocket||Hs.MozWebSocket,cn={websocket:class extends an{createSocket(t,e,i){return nn?new on(t,e,i):e?new on(t,e):new on(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends Gs{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=function(t,e){Ls||(Ls=new TextDecoder);const i=[];let r=0,s=-1,n=!1;return new TransformStream({transform(a,o){for(i.push(a);;){if(0===r){if(Ms(i)<1)break;const t=Fs(i,1);n=!(128&~t[0]),s=127&t[0],r=s<126?3:126===s?1:2}else if(1===r){if(Ms(i)<2)break;const t=Fs(i,2);s=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),r=3}else if(2===r){if(Ms(i)<8)break;const t=Fs(i,8),e=new DataView(t.buffer,t.byteOffset,t.length),n=e.getUint32(0);if(n>Math.pow(2,21)-1){o.enqueue(Is);break}s=n*Math.pow(2,32)+e.getUint32(4),r=3}else{if(Ms(i)<s)break;const t=Fs(i,s);o.enqueue(Ts(n?t:Ls.decode(t),e)),r=0}if(0===s||s>t){o.enqueue(Is);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=t.readable.pipeThrough(e).getReader(),r=new TransformStream({transform(t,e){!function(t,e){ks&&t.data instanceof Blob?t.data.arrayBuffer().then(Ps).then(e):Ss&&(t.data instanceof ArrayBuffer||Es(t.data))?e(Ps(t.data)):xs(t,!1,t=>{As||(As=new TextEncoder),e(As.encode(t))})}(t,i=>{const r=i.length;let s;if(r<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,r);else if(r<65536){s=new Uint8Array(3);const t=new DataView(s.buffer);t.setUint8(0,126),t.setUint16(1,r)}else{s=new Uint8Array(9);const t=new DataView(s.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(r))}t.data&&"string"!=typeof t.data&&(s[0]|=128),e.enqueue(s),e.enqueue(i)})}});r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const s=()=>{i.read().then(({done:t,value:e})=>{t||(this.onPacket(e),s())}).catch(t=>{})};s();const n={type:"open"};this.query.sid&&(n.data=`{"sid":"${this.query.sid}"}`),this._writer.write(n).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const i=t[e],r=e===t.length-1;this._writer.write(i).then(()=>{r&&Ds(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends Qs{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=rn&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new tn(sn,this.uri(),t)}}},hn=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,un=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function dn(t){if(t.length>8e3)throw"URI too long";const e=t,i=t.indexOf("["),r=t.indexOf("]");-1!=i&&-1!=r&&(t=t.substring(0,i)+t.substring(i,r).replace(/:/g,";")+t.substring(r,t.length));let s=hn.exec(t||""),n={},a=14;for(;a--;)n[un[a]]=s[a]||"";return-1!=i&&-1!=r&&(n.source=e,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=function(t,e){const i=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||i.splice(0,1),"/"==e.slice(-1)&&i.splice(i.length-1,1),i}(0,n.path),n.queryKey=function(t,e){const i={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,r){e&&(i[e]=r)}),i}(0,n.query),n}const ln="function"==typeof addEventListener&&"function"==typeof removeEventListener,fn=[];ln&&addEventListener("offline",()=>{fn.forEach(t=>t())},!1);class pn extends Us{constructor(t,e){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const i=dn(t);e.hostname=i.host,e.secure="https"===i.protocol||"wss"===i.protocol,e.port=i.port,i.query&&(e.query=i.query)}else e.host&&(e.hostname=dn(e.host).host);$s(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(t=>{const e=t.prototype.name;this.transports.push(e),this._transportsByName[e]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},i=t.split("&");for(let t=0,r=i.length;t<r;t++){let r=i[t].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}(this.opts.query)),ln&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},fn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const i=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](i)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&pn.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",pn.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e<this.writeBuffer.length;e++){const i=this.writeBuffer[e].data;if(i&&(t+=js(i)),e>0&&t>this._maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Ds(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,i){return this._sendPacket("message",t,e,i),this}send(t,e,i){return this._sendPacket("message",t,e,i),this}_sendPacket(t,e,i,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof i&&(r=i,i=null),"closing"===this.readyState||"closed"===this.readyState)return;(i=i||{}).compress=!1!==i.compress;const s={type:t,data:e,options:i};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},i=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?i():t()}):this.upgrading?i():t()),this}_onError(t){if(pn.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ln&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=fn.indexOf(this._offlineEventListener);-1!==t&&fn.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}pn.protocol=4;class gn extends pn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),i=!1;pn.priorWebsocketSuccess=!1;const r=()=>{i||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!i)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;pn.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{i||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function s(){i||(i=!0,h(),e.close(),e=null)}const n=t=>{const i=new Error("probe error: "+t);i.transport=e.name,s(),this.emitReserved("upgradeError",i)};function a(){n("transport closed")}function o(){n("socket closed")}function c(t){e&&t.name!==e.name&&s()}const h=()=>{e.removeListener("open",r),e.removeListener("error",n),e.removeListener("close",a),this.off("close",o),this.off("upgrading",c)};e.once("open",r),e.once("error",n),e.once("close",a),this.once("close",o),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{i||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let i=0;i<t.length;i++)~this.transports.indexOf(t[i])&&e.push(t[i]);return e}}class yn extends gn{constructor(t,e={}){const i="object"==typeof t?t:e;(!i.transports||i.transports&&"string"==typeof i.transports[0])&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(t=>cn[t]).filter(t=>!!t)),super(t,i)}}const bn="function"==typeof ArrayBuffer,mn=Object.prototype.toString,wn="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===mn.call(Blob),vn="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===mn.call(File);function In(t){return bn&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||wn&&t instanceof Blob||vn&&t instanceof File}function kn(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,i=t.length;e<i;e++)if(kn(t[e]))return!0;return!1}if(In(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return kn(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&kn(t[e]))return!0;return!1}function Sn(t){const e=[],i=t.data,r=t;return r.data=En(i,e),r.attachments=e.length,{packet:r,buffers:e}}function En(t,e){if(!t)return t;if(In(t)){const i={_placeholder:!0,num:e.length};return e.push(t),i}if(Array.isArray(t)){const i=new Array(t.length);for(let r=0;r<t.length;r++)i[r]=En(t[r],e);return i}if("object"==typeof t&&!(t instanceof Date)){const i={};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(i[r]=En(t[r],e));return i}return t}function xn(t,e){return t.data=_n(t.data,e),delete t.attachments,t}function _n(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let i=0;i<t.length;i++)t[i]=_n(t[i],e);else if("object"==typeof t)for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=_n(t[i],e));return t}const Pn=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],An=5;var Nn;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(Nn||(Nn={}));class On{constructor(t){this.replacer=t}encode(t){return t.type!==Nn.EVENT&&t.type!==Nn.ACK||!kn(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===Nn.EVENT?Nn.BINARY_EVENT:Nn.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==Nn.BINARY_EVENT&&t.type!==Nn.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=Sn(t),i=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(i),r}}function Tn(t){return"[object Object]"===Object.prototype.toString.call(t)}class Cn extends Us{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const i=e.type===Nn.BINARY_EVENT;i||e.type===Nn.BINARY_ACK?(e.type=i?Nn.EVENT:Nn.ACK,this.reconstructor=new Rn(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!In(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const i={type:Number(t.charAt(0))};if(void 0===Nn[i.type])throw new Error("unknown packet type "+i.type);if(i.type===Nn.BINARY_EVENT||i.type===Nn.BINARY_ACK){const r=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const s=t.substring(r,e);if(s!=Number(s)||"-"!==t.charAt(e))throw new Error("Illegal attachments");i.attachments=Number(s)}if("/"===t.charAt(e+1)){const r=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);i.nsp=t.substring(r,e)}else i.nsp="/";const r=t.charAt(e+1);if(""!==r&&Number(r)==r){const r=e+1;for(;++e;){const i=t.charAt(e);if(null==i||Number(i)!=i){--e;break}if(e===t.length)break}i.id=Number(t.substring(r,e+1))}if(t.charAt(++e)){const r=this.tryParse(t.substr(e));if(!Cn.isPayloadValid(i.type,r))throw new Error("invalid payload");i.data=r}return i}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case Nn.CONNECT:return Tn(e);case Nn.DISCONNECT:return void 0===e;case Nn.CONNECT_ERROR:return"string"==typeof e||Tn(e);case Nn.EVENT:case Nn.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===Pn.indexOf(e[0]));case Nn.ACK:case Nn.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Rn{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=xn(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function Bn(t,e,i){return t.on(e,i),function(){t.off(e,i)}}const Ln=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Mn extends Us{constructor(t,e,i){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[Bn(t,"open",this.onopen.bind(this)),Bn(t,"packet",this.onpacket.bind(this)),Bn(t,"error",this.onerror.bind(this)),Bn(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var i,r,s;if(Ln.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const n={type:Nn.EVENT,data:e,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,i=e.pop();this._registerAckCallback(t,i),n.id=t}const a=null===(r=null===(i=this.io.engine)||void 0===i?void 0:i.transport)||void 0===r?void 0:r.writable,o=this.connected&&!(null===(s=this.io.engine)||void 0===s?void 0:s._hasPingExpired());return this.flags.volatile&&!a||(o?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(t,e){var i;const r=null!==(i=this.flags.timeout)&&void 0!==i?i:this._opts.ackTimeout;if(void 0===r)return void(this.acks[t]=e);const s=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},r),n=(...t)=>{this.io.clearTimeoutFn(s),e.apply(this,t)};n.withError=!0,this.acks[t]=n}emitWithAck(t,...e){return new Promise((i,r)=>{const s=(t,e)=>t?r(t):i(e);s.withError=!0,e.push(s),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const i={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...r)=>{if(i===this._queue[0])return null!==t?i.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...r)),i.pending=!1,this._drainQueue()}),this._queue.push(i),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:Nn.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case Nn.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Nn.EVENT:case Nn.BINARY_EVENT:this.onevent(t);break;case Nn.ACK:case Nn.BINARY_ACK:this.onack(t);break;case Nn.DISCONNECT:this.ondisconnect();break;case Nn.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const i of e)i.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let i=!1;return function(...r){i||(i=!0,e.packet({type:Nn.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Nn.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let i=0;i<e.length;i++)if(t===e[i])return e.splice(i,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let i=0;i<e.length;i++)if(t===e[i])return e.splice(i,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const i of e)i.apply(this,t.data)}}}function Fn(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}Fn.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),i=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+i:t-i}return 0|Math.min(t,this.max)},Fn.prototype.reset=function(){this.attempts=0},Fn.prototype.setMin=function(t){this.ms=t},Fn.prototype.setMax=function(t){this.max=t},Fn.prototype.setJitter=function(t){this.jitter=t};class Un extends Us{constructor(t,e){var r;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,$s(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=e.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new Fn({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const s=e.parser||i;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new yn(this.uri,this.opts);const e=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const r=Bn(e,"open",function(){i.onopen(),t&&t()}),s=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},n=Bn(e,"error",s);if(!1!==this._timeout){const t=this._timeout,i=this.setTimeoutFn(()=>{r(),s(new Error("timeout")),e.close()},t);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}return this.subs.push(r),this.subs.push(n),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Bn(t,"ping",this.onping.bind(this)),Bn(t,"data",this.ondata.bind(this)),Bn(t,"error",this.onerror.bind(this)),Bn(t,"close",this.onclose.bind(this)),Bn(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){Ds(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let i=this.nsps[t];return i?this._autoConnect&&!i.active&&i.connect():(i=new Mn(this,t,e),this.nsps[t]=i),i}_destroy(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let i=0;i<e.length;i++)this.engine.write(e[i],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var i;this.cleanup(),null===(i=this.engine)||void 0===i||i.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const i=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Dn={};function Hn(t,e){"object"==typeof t&&(e=t,t=void 0);const i=function(t,e="",i){let r=t;i=i||"undefined"!=typeof location&&location,null==t&&(t=i.protocol+"//"+i.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?i.protocol+t:i.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==i?i.protocol+"//"+t:"https://"+t),r=dn(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const s=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+s+":"+r.port+e,r.href=r.protocol+"://"+s+(i&&i.port===r.port?"":":"+r.port),r}(t,(e=e||{}).path||"/socket.io"),r=i.source,s=i.id,n=i.path,a=Dn[s]&&n in Dn[s].nsps;let o;return e.forceNew||e["force new connection"]||!1===e.multiplex||a?o=new Un(r,e):(Dn[s]||(Dn[s]=new Un(r,e)),o=Dn[s]),i.query&&!e.query&&(e.query=i.queryKey),o.socket(i.path,e)}Object.assign(Hn,{Manager:Un,Socket:Mn,io:Hn,connect:Hn});class qn{socket;onDataCallback;constructor(t){this.socket=t,this.socket.on("authMessage",async t=>{void 0!==this.onDataCallback&&await this.onDataCallback(t)})}async send(t){this.socket.emit("authMessage",t)}async onData(t){this.onDataCallback=t}}class Vn{ioSocket;peer;connected=!1;id="";serverIdentityKey;eventCallbacks=new Map;constructor(t,e){this.ioSocket=t,this.peer=e,this.ioSocket.on("connect",()=>{this.connected=!0,this.id=this.ioSocket.id??"",this.fireEventCallbacks("connect")}),this.ioSocket.on("disconnect",t=>{this.connected=!1,this.fireEventCallbacks("disconnect",t)}),this.peer.listenForGeneralMessages((t,e)=>{this.serverIdentityKey=t;const{eventName:i,data:r}=this.decodeEventPayload(e);this.fireEventCallbacks(i,r)})}on(t,e){let i=this.eventCallbacks.get(t);return void 0===i&&(i=[],this.eventCallbacks.set(t,i)),i.push(e),this}emit(t,e){const i=this.encodeEventPayload(t,e);return this.peer.toPeer(i,this.serverIdentityKey).catch(e=>{console.error(`BRC103IoClientSocket emit error for event "${t}":`,e)}),this}disconnect(){this.serverIdentityKey=void 0,this.ioSocket.disconnect()}fireEventCallbacks(t,e){const i=this.eventCallbacks.get(t);if(void 0!==i)for(const t of i)t(e)}encodeEventPayload(t,e){const i={eventName:t,data:e};return Wt(JSON.stringify(i),"utf8")}decodeEventPayload(t){try{const e=Yt(t);return JSON.parse(e)}catch{return{eventName:"_unknown",data:void 0}}}}let Kn=!1;function $n(...t){Kn&&console.log(...t)}function jn(...t){Kn&&console.warn(...t)}function zn(...t){console.error(...t)}class Wn{host;authFetch;walletClient;socket;myIdentityKey;joinedRooms=new Set;lookupResolver;networkPreset;initialized=!1;originator;constructor(t={}){const{host:e,walletClient:i,enableLogging:r=!1,networkPreset:s="mainnet",originator:n}=t,a="testnet"===this.networkPreset?"https://staging-messagebox.babbage.systems":"https://messagebox.babbage.systems";this.host=e?.trim()??a,this.originator=n,this.walletClient=i??new Xr("auto",n),this.authFetch=new os(this.walletClient,void 0,void 0,n),this.networkPreset=s,this.lookupResolver=new ys({networkPreset:s}),r&&(Kn=!0)}async init(t=this.host){const e=t?.trim();if(""===e)throw new Error("Cannot anoint host: No valid host provided");if(e!==this.host&&(this.initialized=!1,this.host=e),this.initialized)return;const i=await this.getIdentityKey(),[r]=await this.queryAdvertisements(i,e);if(null==r||""===r?.host?.trim()||r?.host!==e){$n("[MB CLIENT] Anointing host:",e);try{const{txid:t}=await this.anointHost(e);if(null==t||""===t.trim())throw new Error("Failed to anoint host: No transaction ID returned")}catch(t){$n("[MB CLIENT] Failed to anoint host, continuing with default functionality:",t)}}this.initialized=!0}async assertInitialized(){this.initialized&&null!=this.host&&""!==this.host.trim()||await this.init()}getJoinedRooms(){return this.joinedRooms}async getIdentityKey(){if(null!=this.myIdentityKey&&""!==this.myIdentityKey.trim())return this.myIdentityKey;$n("[MB CLIENT] Fetching identity key...");try{const t=await this.walletClient.getPublicKey({identityKey:!0},this.originator);return this.myIdentityKey=t.publicKey,$n(`[MB CLIENT] Identity key fetched: ${this.myIdentityKey}`),this.myIdentityKey}catch(t){throw zn("[MB CLIENT ERROR] Failed to fetch identity key:",t),new Error("Identity key retrieval failed")}}get testSocket(){return this.socket}async initializeConnection(t){if($n("[MB CLIENT] initializeConnection() STARTED"),null!=this.myIdentityKey&&""!==this.myIdentityKey.trim()||await this.getIdentityKey(),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw zn("[MB CLIENT ERROR] Identity key is still missing after retrieval!"),new Error("Identity key is missing");if($n("[MB CLIENT] Setting up WebSocket connection..."),null==this.socket){const e=t??this.host;if("string"!=typeof e||""===e.trim())throw new Error("Cannot initialize WebSocket: No valid host provided");this.socket=function(t,e){const i=Hn(t,e.managerOptions),r=new qn(i),s=new ss(e.wallet,r,e.requestedCertificates,e.sessionManager,void 0,e.originator);return new Vn(i,s)}(e,{wallet:this.walletClient,originator:this.originator});let i=!1,r=!1;this.socket.on("connect",()=>{$n("[MB CLIENT] Connected to WebSocket."),i||($n("[MB CLIENT] Sending authentication data:",this.myIdentityKey),null==this.myIdentityKey||""===this.myIdentityKey.trim()?zn("[MB CLIENT ERROR] Cannot send authentication: Identity key is missing!"):(this.socket?.emit("authenticated",{identityKey:this.myIdentityKey}),i=!0))}),this.socket.on("authenticationSuccess",t=>{$n(`[MB CLIENT] WebSocket authentication successful: ${JSON.stringify(t)}`),r=!0}),this.socket.on("authenticationFailed",t=>{zn(`[MB CLIENT ERROR] WebSocket authentication failed: ${JSON.stringify(t)}`),r=!1}),this.socket.on("disconnect",()=>{$n("[MB CLIENT] Disconnected from MessageBox server"),this.socket=void 0,i=!1,r=!1}),this.socket.on("error",t=>{zn("[MB CLIENT ERROR] WebSocket error:",t)}),await new Promise((t,e)=>{setTimeout(()=>{r?($n("[MB CLIENT] WebSocket fully authenticated and ready!"),t()):e(new Error("[MB CLIENT ERROR] WebSocket authentication timed out!"))},5e3)})}}async resolveHostForRecipient(t){const e=await this.queryAdvertisements(t,void 0);return 0===e.length?(jn(`[MB CLIENT] No advertisements for ${t}, using default host ${this.host}`),this.host):e[0].host}async queryAdvertisements(t,e){const i=[];try{const r={identityKey:t??await this.getIdentityKey()};null!=e&&""!==e.trim()&&(r.host=e);const s=await this.lookupResolver.query({service:"ls_messagebox",query:r});if("output-list"!==s.type)throw new Error(`Unexpected result type: ${String(s.type)}`);for(const t of s.outputs)try{const e=ir.fromBEEF(t.beef),r=e.outputs[t.outputIndex].lockingScript,s=Di.decode(r),[,n]=s.fields;if(null==n||0===n.length)throw new Error("Empty host field");i.push({host:Yt(n),txid:e.id("hex"),outputIndex:t.outputIndex,lockingScript:r,beef:t.beef})}catch{}}catch(t){zn("[MB CLIENT ERROR] _queryAdvertisements failed:",t)}return i}async joinRoom(t,e){if($n(`[MB CLIENT] Attempting to join WebSocket room: ${t}`),null==this.socket&&($n("[MB CLIENT] No WebSocket connection. Initializing..."),await this.initializeConnection(e)),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw new Error("[MB CLIENT ERROR] Identity key is not defined");const i=`${this.myIdentityKey??""}-${t}`;if(this.joinedRooms.has(i))$n(`[MB CLIENT] Already joined WebSocket room: ${i}`);else try{$n(`[MB CLIENT] Joining WebSocket room: ${i}`),await(this.socket?.emit("joinRoom",i)),this.joinedRooms.add(i),$n(`[MB CLIENT] Successfully joined room: ${i}`)}catch(t){zn(`[MB CLIENT ERROR] Failed to join WebSocket room: ${i}`,t)}}async listenForLiveMessages({onMessage:t,messageBox:e,overrideHost:i}){if($n(`[MB CLIENT] Setting up listener for WebSocket room: ${e}`),null==this.socket&&($n("[MB CLIENT] No WebSocket connection. Initializing..."),await this.initializeConnection(i)),await this.joinRoom(e,this.originator),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw new Error("[MB CLIENT ERROR] Identity key is missing. Cannot construct room ID.");const r=`${this.myIdentityKey}-${e}`;$n(`[MB CLIENT] Listening for messages in room: ${r}`),this.socket?.on(`sendMessage-${r}`,e=>{(async()=>{$n(`[MB CLIENT] Received message in room ${r}:`,e);try{let t=e.body;if("string"==typeof t)try{t=JSON.parse(t)}catch{}if(null!=t&&"object"==typeof t&&"string"==typeof t.encryptedMessage){$n(`[MB CLIENT] Decrypting message from ${String(e.sender)}...`);const i=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:e.sender,ciphertext:Wt(t.encryptedMessage,"base64")},this.originator);e.body=Yt(i.plaintext)}else $n("[MB CLIENT] Message is not encrypted."),e.body="string"==typeof t?t:(()=>{try{return JSON.stringify(t)}catch{return"[Error: Unstringifiable message]"}})()}catch(t){zn("[MB CLIENT ERROR] Failed to parse or decrypt live message:",t),e.body="[Error: Failed to decrypt or parse message]"}t(e)})()})}async sendLiveMessage({recipient:t,messageBox:e,body:i,messageId:r,skipEncryption:s,checkPermissions:n},a){if(null==t||""===t.trim())throw new Error("[MB CLIENT ERROR] Recipient identity key is required");if(null==e||""===e.trim())throw new Error("[MB CLIENT ERROR] MessageBox is required");if(null==i||"string"==typeof i&&""===i.trim())throw new Error("[MB CLIENT ERROR] Message body cannot be empty");if(await this.joinRoom(e,this.originator),null==this.socket||!this.socket.connected){jn("[MB CLIENT WARNING] WebSocket not connected, falling back to HTTP");const r=a??await this.resolveHostForRecipient(t);return await this.sendMessage({recipient:t,messageBox:e,body:i},r)}let o;try{const e=await this.walletClient.createHmac({data:Array.from((new TextEncoder).encode(JSON.stringify(i))),protocolID:[1,"messagebox"],keyID:"1",counterparty:t},this.originator);o=r??Array.from(e.hmac).map(t=>t.toString(16).padStart(2,"0")).join("")}catch(t){throw zn("[MB CLIENT ERROR] Failed to generate HMAC:",t),new Error("Failed to generate message identifier.")}const c=`${t}-${e}`;let h;if($n(`[MB CLIENT] Sending WebSocket message to room: ${c}`),!0===s)h="string"==typeof i?i:JSON.stringify(i);else{const e=await this.walletClient.encrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t,plaintext:Wt("string"==typeof i?i:JSON.stringify(i),"utf8")},this.originator);h=JSON.stringify({encryptedMessage:Zt(e.ciphertext)})}return await new Promise((r,a)=>{const u=`sendMessageAck-${c}`;let d=!1;const l=c=>{if(d)return;d=!0;const h=this.socket;if("function"==typeof h?.off&&h.off(u,l),$n("[MB CLIENT] Received WebSocket acknowledgment:",c),null==c||"success"!==c.status){jn("[MB CLIENT] WebSocket message failed or returned unexpected response. Falling back to HTTP.");const c={recipient:t,messageBox:e,body:i,messageId:o,skipEncryption:s,checkPermissions:n};this.resolveHostForRecipient(t).then(async t=>await this.sendMessage(c,t)).then(r).catch(a)}else $n("[MB CLIENT] Message sent successfully via WebSocket:",c),r(c)};this.socket?.on(u,l),this.socket?.emit("sendMessage",{roomId:c,message:{messageId:o,recipient:t,body:h}}),setTimeout(()=>{if(!d){d=!0;const c=this.socket;"function"==typeof c?.off&&c.off(u,l),jn("[CLIENT] WebSocket acknowledgment timed out, falling back to HTTP");const h={recipient:t,messageBox:e,body:i,messageId:o,skipEncryption:s,checkPermissions:n};this.resolveHostForRecipient(t).then(async t=>await this.sendMessage(h,t)).then(r).catch(a)}},1e4)})}async leaveRoom(t){if(await this.assertInitialized(),null==this.socket)return void jn("[MB CLIENT] Attempted to leave a room but WebSocket is not connected.");if(null==this.myIdentityKey||""===this.myIdentityKey.trim())throw new Error("[MB CLIENT ERROR] Identity key is not defined");const e=`${this.myIdentityKey}-${t}`;$n(`[MB CLIENT] Leaving WebSocket room: ${e}`),this.socket.emit("leaveRoom",e),this.joinedRooms.delete(e)}async disconnectWebSocket(){await this.assertInitialized(),null!=this.socket?($n("[MB CLIENT] Closing WebSocket connection..."),this.socket.disconnect(),this.socket=void 0):$n("[MB CLIENT] No active WebSocket connection to close.")}async sendMessage(t,e){if(await this.assertInitialized(),null==t.recipient||""===t.recipient.trim())throw new Error("You must provide a message recipient!");if(null==t.messageBox||""===t.messageBox.trim())throw new Error("You must provide a messageBox to send this message into!");if(null==t.body||"string"==typeof t.body&&0===t.body.trim().length)throw new Error("Every message must have a body!");let i,r,s;if(!0===t.checkPermissions)try{$n("[MB CLIENT] Checking permissions and fees for message...");const r=await this.getMessageBoxQuote({recipient:t.recipient,messageBox:t.messageBox},e);if(-1===r.recipientFee)throw new Error("You have been blocked from sending messages to this recipient.");if(r.recipientFee>0||r.deliveryFee>0){const s=r.recipientFee+r.deliveryFee;s>0&&($n(`[MB CLIENT] Creating payment of ${s} sats for message...`),i=await this.createMessagePayment(t.recipient,r,e),$n("[MB CLIENT] Payment data prepared:",i))}}catch(t){throw new Error(`Permission check failed: ${t instanceof Error?t.message:"Unknown error"}`)}try{const e=await this.walletClient.createHmac({data:Array.from((new TextEncoder).encode(JSON.stringify(t.body))),protocolID:[1,"messagebox"],keyID:"1",counterparty:t.recipient},this.originator);r=t.messageId??Array.from(e.hmac).map(t=>t.toString(16).padStart(2,"0")).join("")}catch(t){throw zn("[MB CLIENT ERROR] Failed to generate HMAC:",t),new Error("Failed to generate message identifier.")}if(!0===t.skipEncryption)s="string"==typeof t.body?t.body:JSON.stringify(t.body);else{const e=await this.walletClient.encrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t.recipient,plaintext:Wt("string"==typeof t.body?t.body:JSON.stringify(t.body),"utf8")},this.originator);s=JSON.stringify({encryptedMessage:Zt(e.ciphertext)})}const n={message:{...t,messageId:r,body:s},...null!=i&&{payment:i}};try{const i=e??await this.resolveHostForRecipient(t.recipient);if($n("[MB CLIENT] Sending HTTP request to:",`${i}/sendMessage`),$n("[MB CLIENT] Request Body:",JSON.stringify(n,null,2)),null==this.myIdentityKey||""===this.myIdentityKey)try{const t=await this.walletClient.getPublicKey({identityKey:!0},this.originator);this.myIdentityKey=t.publicKey,$n(`[MB CLIENT] Fetched identity key before sending request: ${this.myIdentityKey}`)}catch(t){throw zn("[MB CLIENT ERROR] Failed to fetch identity key:",t),new Error("Identity key retrieval failed")}const s=await this.authFetch.fetch(`${i}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(s.bodyUsed)throw new Error("[MB CLIENT ERROR] Response body has already been used!");const a=await s.json();if($n("[MB CLIENT] Raw Response Body:",a),!s.ok)throw zn(`[MB CLIENT ERROR] Failed to send message. HTTP ${s.status}: ${s.statusText}`),new Error(`Message sending failed: HTTP ${s.status} - ${s.statusText}`);if("success"!==a.status)throw zn(`[MB CLIENT ERROR] Server returned an error: ${String(a.description)}`),new Error(a.description??"Unknown error from server.");return $n("[MB CLIENT] Message successfully sent."),{...a,messageId:r}}catch(t){zn("[MB CLIENT ERROR] Network or timeout error:",t);const e=t instanceof Error?t.message:"Unknown error";throw new Error(`Failed to send message: ${e}`)}}async sendMesagetoRecepients(t,e){await this.assertInitialized();const{recipients:i,messageBox:r,body:s,skipEncryption:n}=t;if(!Array.isArray(i)||0===i.length)throw new Error("You must provide at least one recipient!");if(!r||""===r.trim())throw new Error("You must provide a messageBox to send this message into!");if(null==s||"string"==typeof s&&0===s.trim().length)throw new Error("Every message must have a body!");const a=await this.getMessageBoxQuote({recipient:i,messageBox:r},e),o=Array.isArray(a?.quotesByRecipient)?a.quotesByRecipient:[],c=a?.blockedRecipients??[],h=a?.totals,u=i.filter(t=>!c.includes(t));if(0===u.length)return{status:"error",description:`All ${i.length} recipients are blocked.`,sent:[],blocked:c,failed:i.map(t=>({recipient:t,error:"blocked"})),totals:h};const d=new Map;for(const t of o)d.set(t.recipient,{recipientFee:t.recipientFee,deliveryFee:t.deliveryFee});const{deliveryAgentIdentityKeyByHost:l}=a;if(!l||0===Object.keys(l).length)throw new Error("Missing delivery agent identity keys in quote response.");if(Object.keys(l).length>1&&!e)throw new Error("Recipients resolve to multiple hosts. Use overrideHost to force a single server or split by host.");const f=(e??await this.resolveHostForRecipient(u[0])).replace(/\/+$/,""),p=l[f]??Object.values(l)[0];if(!p)throw new Error("Could not determine server delivery agent identity key.");if(!this.myIdentityKey){const t=await this.walletClient.getPublicKey({identityKey:!0},this.originator);this.myIdentityKey=t.publicKey}const g=Array.from((new TextEncoder).encode(JSON.stringify(s))),y=await this.mapWithConcurrency(u,8,async t=>{const e=await this.walletClient.createHmac({data:g,protocolID:[1,"messagebox"],keyID:"1",counterparty:t},this.originator);return Array.from(e.hmac).map(t=>t.toString(16).padStart(2,"0")).join("")});let b;b="string"==typeof s?s:JSON.stringify(s);const m=await this.createMessagePaymentBatch(u,d,p),w={message:{recipients:u,messageBox:r,messageId:y,body:b},payment:m};$n("[MB CLIENT] Sending HTTP request to:",`${f}/sendMessage`),$n("[MB CLIENT] Request Body (batch):",JSON.stringify({...w,payment:{...m,tx:"<omitted>"}},null,2));try{const t=await this.authFetch.fetch(`${f}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)}),e=await t.json().catch(()=>({}));if(!t.ok||"success"!==e.status){const i=t.ok?e.description??"Unknown server error":`HTTP ${t.status} - ${t.statusText}`;throw new Error(i)}const i=Array.isArray(e.results)?e.results:[],r=[],s=i.length===u.length?"success":i.length>0?"partial":"error";return{status:s,description:"success"===s?`Sent to ${i.length} recipients.`:"partial"===s?`Sent to ${i.length} recipients; ${u.length-i.length} failed; ${c.length} blocked.`:`Failed to send to ${u.length} allowed recipients. ${c.length} blocked.`,sent:i,blocked:c,failed:r,totals:h}}catch(t){const e=t instanceof Error?t.message:"Unknown error";return{status:"error",description:`Batch send failed: ${e}`,sent:[],blocked:c,failed:u.map(t=>({recipient:t,error:e})),totals:h}}}async anointHost(t){$n("[MB CLIENT] Starting anointHost...");try{if(!t.startsWith("http"))throw new Error("Invalid host URL");const e=await this.getIdentityKey();$n("[MB CLIENT] Fields - Identity:",e,"Host:",t);const i=[Wt(e,"hex"),Wt(t,"utf8")],r=new Di(this.walletClient,this.originator);$n("Fields:",i.map(t=>jt(t))),$n("ProtocolID:",[1,"messagebox advertisement"]),$n("KeyID:","1"),$n("SignAs:","self"),$n("anyoneCanSpend:",!1),$n("forSelf:",!0);const s=await r.lock(i,[1,"messagebox advertisement"],"1","anyone",!0);$n("[MB CLIENT] PushDrop script:",s.toASM());const{tx:n,txid:a}=await this.walletClient.createAction({description:"Anoint host for overlay routing",outputs:[{basket:"overlay advertisements",lockingScript:s.toHex(),satoshis:1,outputDescription:"Overlay advertisement output"}],options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1}},this.originator);if($n("[MB CLIENT] Transaction created:",a),void 0!==n){const t=new ms(["tm_messagebox"],{networkPreset:this.networkPreset}),e=await t.broadcast(ir.fromAtomicBEEF(n));if($n("[MB CLIENT] Advertisement broadcast succeeded. TXID:",e.txid),"string"!=typeof e.txid)throw new Error("Anoint failed: broadcast did not return a txid");return{txid:e.txid}}throw new Error("Anoint failed: failed to create action!")}catch(t){throw zn("[MB CLIENT ERROR] anointHost threw:",t),t}}async revokeHostAdvertisement(t){$n("[MB CLIENT] Starting revokeHost...");const e=`${t.txid}.${t.outputIndex}`;try{const{signableTransaction:i}=await this.walletClient.createAction({description:"Revoke MessageBox host advertisement",inputBEEF:t.beef,inputs:[{outpoint:e,unlockingScriptLength:73,inputDescription:"Revoking host advertisement token"}]},this.originator);if(void 0===i)throw new Error("Failed to create signable transaction.");const r=ir.fromBEEF(i.tx),s=new Di(this.walletClient,this.originator),n=await s.unlock([1,"messagebox advertisement"],"1","anyone","all",!1,t.outputIndex,t.lockingScript),a=await n.sign(r,t.outputIndex),{tx:o}=await this.walletClient.signAction({reference:i.reference,spends:{[t.outputIndex]:{unlockingScript:a.toHex()}},options:{acceptDelayedBroadcast:!1}},this.originator);if(void 0===o)throw new Error("Failed to finalize the transaction signature.");const c=new ms(["tm_messagebox"],{networkPreset:this.networkPreset}),h=await c.broadcast(ir.fromAtomicBEEF(o));if($n("[MB CLIENT] Revocation broadcast succeeded. TXID:",h.txid),"string"!=typeof h.txid)throw new Error("Revoke failed: broadcast did not return a txid");return{txid:h.txid}}catch(t){throw zn("[MB CLIENT ERROR] revokeHost threw:",t),t}}async listMessages({messageBox:t,host:e,acceptPayments:i}){if("boolean"!=typeof i&&(i=!0),""===t.trim())throw new Error("MessageBox cannot be empty");let r=null!=e?[e]:[];if(0===r.length){const t=await this.queryAdvertisements(await this.getIdentityKey(),void 0);r=Array.from(new Set([this.host,...t.map(t=>t.host)]))}const s=await Promise.allSettled(r.map(async e=>{try{$n(`[MB CLIENT] Listing messages from ${e}…`);const i=await this.authFetch.fetch(`${e}/listMessages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageBox:t})});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);const r=await i.json();if("error"===r.status)throw new Error(r.description??"Unknown server error");return r.messages}catch(t){throw $n(`[MB CLIENT DEBUG] listMessages failed for ${e}:`,t),t}})),n=[],a=[];for(const t of s)"fulfilled"===t.status?n.push(t.value):a.push(t.reason);if(0===n.length)throw new Error("Failed to retrieve messages from any host");const o=new Map;for(const t of n)for(const e of t)o.has(e.messageId)||o.set(e.messageId,e);if(0===o.size)return[];const c=Array.from(o.values()),h=c.map(t=>{const e="string"==typeof t.body?this.tryParse(t.body):t.body;let i,r=e;if(null!=e&&"object"==typeof e&&"message"in e){const t=e.message;r="string"==typeof t?this.tryParse(t):t,i=e.payment}return{message:t,parsedBody:e,messageContent:r,paymentData:i}});if(i){const t=h.filter(t=>null!=t.paymentData?.tx&&null!=t.paymentData.outputs);await this.mapWithConcurrency(t,2,async t=>{try{$n(`[MB CLIENT] Processing recipient payment in message from ${String(t.message.sender)}…`);const e=t.paymentData.outputs.filter(t=>"wallet payment"===t.protocol);e.length>0?($n(`[MB CLIENT] Internalizing ${e.length} recipient payment output(s)…`),(await this.walletClient.internalizeAction({tx:t.paymentData.tx,outputs:e,description:t.paymentData.description??"MessageBox recipient payment"},this.originator)).accepted?$n("[MB CLIENT] Successfully internalized recipient payment"):jn("[MB CLIENT] Recipient payment internalization was not accepted")):$n("[MB CLIENT] No wallet payment outputs found in payment data")}catch(t){zn("[MB CLIENT ERROR] Failed to internalize recipient payment:",t)}return null})}return await this.mapWithConcurrency(h,4,async t=>{try{if(null!=t.messageContent&&"object"==typeof t.messageContent&&"string"==typeof t.messageContent.encryptedMessage){$n(`[MB CLIENT] Decrypting message from ${String(t.message.sender)}…`);const e=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t.message.sender,ciphertext:Wt(t.messageContent.encryptedMessage,"base64")},this.originator),i=Yt(e.plaintext);t.message.body=this.tryParse(i)}else t.message.body=t.messageContent??t.parsedBody}catch(e){zn("[MB CLIENT ERROR] Failed to parse or decrypt message in list:",e),t.message.body="[Error: Failed to decrypt or parse message]"}return null}),c.sort((t,e)=>Number(e.timestamp??0)-Number(t.timestamp??0)),c}async listMessagesLite({messageBox:t,host:e}){const i=await this.authFetch.fetch(`${e}/listMessages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageBox:t})}),r=await i.json();if("error"===r.status)throw new Error(r.description??"Unknown server error");const s=r.messages,n=t=>{try{return JSON.parse(t)}catch{return t}};return await this.mapWithConcurrency(s,4,async t=>{try{const e="string"==typeof t.body?n(t.body):t.body;let i=e;if(null!=e&&"object"==typeof e&&"message"in e){const t=e.message;i="string"==typeof t?n(t):t}if(null!=i&&"object"==typeof i&&"string"==typeof i.encryptedMessage){const e=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t.sender,ciphertext:Wt(i.encryptedMessage,"base64")}),r=Yt(e.plaintext);t.body=n(r)}else t.body=i??e}catch(e){zn("[MB CLIENT ERROR] Failed to parse or decrypt message in list:",e),t.body="[Error: Failed to decrypt or parse message]"}return null}),s}tryParse(t){try{return JSON.parse(t)}catch{return t}}async mapWithConcurrency(t,e,i){if(0===t.length)return[];if(!Number.isFinite(e)||e>=t.length)return await Promise.all(t.map(i));const r=Math.max(1,Math.min(e,t.length)),s=new Array(t.length);let n=0;const a=Array.from({length:r},async()=>{for(;;){const e=n;if(n++,e>=t.length)return;s[e]=await i(t[e],e)}});return await Promise.all(a),s}async acknowledgeNotification(t){await this.acknowledgeMessage({messageIds:[t.messageId]});const e="string"==typeof t.body?this.tryParse(t.body):t.body;let i;if(null!=e&&"object"==typeof e&&"message"in e&&(i=e.payment),null!=i?.tx&&null!=i.outputs)try{$n(`[MB CLIENT] Processing recipient payment in message from ${String(t.sender)}…`);const e=i.outputs.filter(t=>"wallet payment"===t.protocol);return e.length<1?($n("[MB CLIENT] No wallet payment outputs found in payment data"),!1):($n(`[MB CLIENT] Internalizing ${e.length} recipient payment output(s)…`),(await this.walletClient.internalizeAction({tx:i.tx,outputs:e,description:i.description??"MessageBox recipient payment"})).accepted?($n("[MB CLIENT] Successfully internalized recipient payment"),!0):(jn("[MB CLIENT] Recipient payment internalization was not accepted"),!1))}catch(t){return zn("[MB CLIENT ERROR] Failed to internalize recipient payment:",t),!1}return!1}async acknowledgeMessage({messageIds:t,host:e}){if(!Array.isArray(t)||0===t.length)throw new Error("Message IDs array cannot be empty");$n(`[MB CLIENT] Acknowledging messages ${JSON.stringify(t)}…`);let i=null!=e?[e]:[];if(0===i.length){const t=await this.getIdentityKey(),e=await this.queryAdvertisements(t,void 0);i=Array.from(new Set([this.host,...e.map(t=>t.host)]))}const r=await Promise.allSettled(i.map(async e=>{try{const i=await this.authFetch.fetch(`${e}/acknowledgeMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageIds:t})});if(!i.ok)throw new Error(`HTTP ${i.status}`);const r=await i.json();if("error"===r.status)throw new Error(r.description);return $n(`[MB CLIENT] Acknowledged on ${e}`),r.status}catch(t){return jn(`[MB CLIENT WARN] acknowledgeMessage failed for ${e}:`,t),null}})),s=r.filter(t=>"fulfilled"===t.status),n=s.find(t=>null!=t.value)?.value;if(null!=n)return n;const a=[];for(const t of r)"rejected"===t.status&&a.push(t.reason);throw new Error(`Failed to acknowledge messages on all hosts: ${a.map(t=>String(t)).join("; ")}`)}async setMessageBoxPermission(t,e){const i=e??this.host;$n("[MB CLIENT] Setting messageBox permission...");const r=await this.authFetch.fetch(`${i}/permissions/set`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageBox:t.messageBox,recipientFee:t.recipientFee,...null!=t.sender&&{sender:t.sender}})});if(!r.ok){const t=await r.json().catch(()=>({}));throw new Error(`Failed to set permission: HTTP ${r.status} - ${""!==String(t.description)?String(t.description):r.statusText}`)}const{status:s,description:n}=await r.json();if("error"===s)throw new Error(n??"Failed to set permission")}async getMessageBoxPermission(t,e){const i=e??await this.resolveHostForRecipient(t.recipient),r=new URLSearchParams({recipient:t.recipient,messageBox:t.messageBox,...null!=t.sender&&{sender:t.sender}});$n("[MB CLIENT] Getting messageBox permission...");const s=await this.authFetch.fetch(`${i}/permissions/get?${r.toString()}`,{method:"GET"});if(!s.ok){const t=await s.json().catch(()=>({}));throw new Error(`Failed to get permission: HTTP ${s.status} - ${""!==String(t.description)?String(t.description):s.statusText}`)}const n=await s.json();if("error"===n.status)throw new Error(n.description??"Failed to get permission");return n.permission}async getMessageBoxQuote(t,e){if(!Array.isArray(t.recipient)){const i=e??await this.resolveHostForRecipient(t.recipient),r=new URLSearchParams({recipient:t.recipient,messageBox:t.messageBox});$n("[MB CLIENT] Getting messageBox quote (single)..."),console.log("HELP IM QUOTING",`${i}/permissions/quote?${r.toString()}`);const s=await this.authFetch.fetch(`${i}/permissions/quote?${r.toString()}`,{method:"GET"});if(console.log("server response from getquote]",s),!s.ok){const t=await s.json().catch(()=>({}));throw new Error(`Failed to get quote: HTTP ${s.status} - ${String(t.description)??s.statusText}`)}const{status:n,description:a,quote:o}=await s.json();if("error"===n)throw new Error(a??"Failed to get quote");const c=s.headers.get("x-bsv-auth-identity-key");if(console.log("deliveryAgentIdentityKey",c),null==c)throw new Error("Failed to get quote: Delivery agent did not provide their identity key");return{recipientFee:o.recipientFee,deliveryFee:o.deliveryFee,deliveryAgentIdentityKey:c}}const i=t.recipient;if(0===i.length)throw new Error("At least one recipient is required.");$n("[MB CLIENT] Getting messageBox quotes (multi)..."),console.log("[MB CLIENT] Getting messageBox quotes (multi)...");const r=new Map,s=null!=e?i.map(()=>e):await this.mapWithConcurrency(i,8,async t=>await this.resolveHostForRecipient(t));for(let t=0;t<i.length;t++){const e=i[t],n=s[t],a=r.get(n);null!=a?a.push(e):r.set(n,[e])}const n={},a=[],o=[];let c=0,h=0;const u=async(e,i)=>{const r=new URLSearchParams;for(const t of i)r.append("recipient",t);r.set("messageBox",t.messageBox);const s=`${e}/permissions/quote?${r.toString()}`;$n("[MB CLIENT] Multi-quote GET:",s);const u=await this.authFetch.fetch(s,{method:"GET"});if(!u.ok){const t=await u.json().catch(()=>({}));throw new Error(`Failed to get quote (host ${e}): HTTP ${u.status} - ${String(t.description)??u.statusText}`)}const d=u.headers.get("x-bsv-auth-identity-key");if(!d)throw new Error(`Failed to get quote (host ${e}): missing delivery agent identity key`);n[e]=d;const l=await u.json();if(Array.isArray(l?.quotesByRecipient)){for(const t of l.quotesByRecipient)a.push({recipient:t.recipient,messageBox:t.messageBox,deliveryFee:t.deliveryFee,recipientFee:t.recipientFee,status:t.status}),c+=t.deliveryFee,-1===t.recipientFee?o.includes(t.recipient)||o.push(t.recipient):h+=t.recipientFee;if(Array.isArray(l?.blockedRecipients))for(const t of l.blockedRecipients)o.includes(t)||o.push(t)}else{if(!l?.quote)throw new Error(`Unexpected quote response shape from host ${e}`);for(const e of i){const{deliveryFee:i,recipientFee:r}=l.quote,s=-1===r?"blocked":0===r?"always_allow":"payment_required";a.push({recipient:e,messageBox:t.messageBox,deliveryFee:i,recipientFee:r,status:s}),c+=i,-1===r?o.push(e):h+=r}}};return await Promise.all(Array.from(r.entries()).map(async([t,e])=>await u(t,e))),{quotesByRecipient:a,totals:{deliveryFees:c,recipientFees:h,totalForPayableRecipients:c+h},blockedRecipients:o,deliveryAgentIdentityKeyByHost:n}}async listMessageBoxPermissions(t,e){const i=e??this.host,r=new URLSearchParams;null!=t?.messageBox&&r.set("message_box",t.messageBox),void 0!==t?.limit&&r.set("limit",t.limit.toString()),void 0!==t?.offset&&r.set("offset",t.offset.toString()),$n("[MB CLIENT] Listing messageBox permissions with params:",r.toString());const s=await this.authFetch.fetch(`${i}/permissions/list?${r.toString()}`,{method:"GET"});if(!s.ok){const t=await s.json().catch(()=>({}));throw new Error(`Failed to list permissions: HTTP ${s.status} - ${""!==String(t.description)?String(t.description):s.statusText}`)}const n=await s.json();if("error"===n.status)throw new Error(n.description??"Failed to list permissions");return n.permissions.map(t=>({sender:t.sender,messageBox:t.message_box,recipientFee:t.recipient_fee,status:Wn.getStatusFromFee(t.recipient_fee),createdAt:t.created_at,updatedAt:t.updated_at}))}async allowNotificationsFromPeer(t,e=0,i){await this.setMessageBoxPermission({messageBox:"notifications",sender:t,recipientFee:e},i)}async denyNotificationsFromPeer(t,e){await this.setMessageBoxPermission({messageBox:"notifications",sender:t,recipientFee:-1},e)}async checkPeerNotificationStatus(t,e){const i=await this.getIdentityKey();return await this.getMessageBoxPermission({recipient:i,messageBox:"notifications",sender:t},e)}async listPeerNotifications(t){return await this.listMessageBoxPermissions({messageBox:"notifications"},t)}async sendNotification(t,e,i){return await this.assertInitialized(),Array.isArray(t)?await this.sendMesagetoRecepients({recipients:t,messageBox:"notifications",body:e},i):await this.sendMessage({recipient:t,messageBox:"notifications",body:e,checkPermissions:!0},i)}async registerDevice(t,e){if(null==t.fcmToken||""===t.fcmToken.trim())throw new Error("fcmToken is required and must be a non-empty string");if(null!=t.platform&&!["ios","android","web"].includes(t.platform))throw new Error("platform must be one of: ios, android, web");const i=e??this.host;$n("[MB CLIENT] Registering device for FCM notifications...");const r=await this.authFetch.fetch(`${i}/registerDevice`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fcmToken:t.fcmToken.trim(),deviceId:t.deviceId?.trim()??void 0,platform:t.platform??void 0})});if(!r.ok){const t=await r.json().catch(()=>({})),e=String(t.description)??r.statusText;throw new Error(`Failed to register device: HTTP ${r.status} - ${e}`)}const s=await r.json();if("error"===s.status)throw new Error(s.description??"Failed to register device");return $n("[MB CLIENT] Device registered successfully"),{status:s.status,message:s.message,deviceId:s.deviceId}}async listRegisteredDevices(t){const e=t??this.host;$n("[MB CLIENT] Listing registered devices...");const i=await this.authFetch.fetch(`${e}/devices`,{method:"GET"});if(!i.ok){const t=await i.json().catch(()=>({})),e=String(t.description)??i.statusText;throw new Error(`Failed to list devices: HTTP ${i.status} - ${e}`)}const r=await i.json();if("error"===r.status)throw new Error(r.description??"Failed to list devices");return $n(`[MB CLIENT] Found ${r.devices.length} registered devices`),r.devices}static getStatusFromFee(t){return-1===t?"blocked":0===t?"always_allow":"payment_required"}async createMessagePayment(t,e,i="MessageBox delivery payment"){if(e.recipientFee<=0&&e.deliveryFee<=0)throw new Error("No payment required");$n(`[MB CLIENT] Creating payment transaction for ${e.recipientFee} sats (delivery: ${e.deliveryFee}, recipient: ${e.recipientFee})`);const r=[],s=[],n=await this.getIdentityKey();let a=0;if(e.deliveryFee>0){const t=Zt(We(32)),i=Zt(We(32));console.log("delivery agent:",e.deliveryAgentIdentityKey);const{publicKey:o}=await this.walletClient.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${t} ${i}`,counterparty:e.deliveryAgentIdentityKey},this.originator),c=(new Fi).lock($e.fromString(o).toAddress()).toHex();s.push({satoshis:e.deliveryFee,lockingScript:c,outputDescription:"MessageBox server delivery fee",customInstructions:JSON.stringify({derivationPrefix:t,derivationSuffix:i,recipientIdentityKey:e.deliveryAgentIdentityKey})}),r.push({outputIndex:a++,protocol:"wallet payment",paymentRemittance:{derivationPrefix:t,derivationSuffix:i,senderIdentityKey:n}})}if(e.recipientFee>0){const i=Zt(We(32)),n=Zt(We(32)),o=new ar("anyone"),{publicKey:c}=await o.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${i} ${n}`,counterparty:t});if(null==c||""===c.trim())throw new Error("Failed to derive recipient's public key");const h=(new Fi).lock($e.fromString(c).toAddress()).toHex();s.push({satoshis:e.recipientFee,lockingScript:h,outputDescription:"Recipient message fee",customInstructions:JSON.stringify({derivationPrefix:i,derivationSuffix:n,recipientIdentityKey:t})}),r.push({outputIndex:a++,protocol:"wallet payment",paymentRemittance:{derivationPrefix:i,derivationSuffix:n,senderIdentityKey:(await o.getPublicKey({identityKey:!0})).publicKey}})}const{tx:o}=await this.walletClient.createAction({description:i,outputs:s,options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1}},this.originator);if(null==o)throw new Error("Failed to create payment transaction");return{tx:o,outputs:r,description:i}}async createMessagePaymentBatch(t,e,i,r="MessageBox delivery payment (batch)"){const s=[],n=[],a=t.reduce((t,i)=>{const r=e.get(i);return null!=r?t??r.deliveryFee:t},void 0)??0,o=await this.getIdentityKey();let c=0;if(a>0){const t=Zt(We(32)),e=Zt(We(32)),{publicKey:r}=await this.walletClient.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${t} ${e}`,counterparty:i},this.originator),h=(new Fi).lock($e.fromString(r).toAddress()).toHex();n.push({satoshis:a,lockingScript:h,outputDescription:"MessageBox server delivery fee (batch)",customInstructions:JSON.stringify({derivationPrefix:t,derivationSuffix:e,recipientIdentityKey:i})}),s.push({outputIndex:c++,protocol:"wallet payment",paymentRemittance:{derivationPrefix:t,derivationSuffix:e,senderIdentityKey:o}})}const h=new ar("anyone"),u=(await h.getPublicKey({identityKey:!0})).publicKey;for(const i of t){const t=e.get(i);if(null==t||t.recipientFee<=0)continue;const r=Zt(We(32)),a=Zt(We(32)),{publicKey:o}=await h.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${r} ${a}`,counterparty:i}),d=(new Fi).lock($e.fromString(o).toAddress()).toHex();n.push({satoshis:t.recipientFee,lockingScript:d,outputDescription:`Recipient message fee (${i.slice(0,8)}…)`,customInstructions:JSON.stringify({derivationPrefix:r,derivationSuffix:a,recipientIdentityKey:i})}),s.push({outputIndex:c++,protocol:"wallet payment",paymentRemittance:{derivationPrefix:r,derivationSuffix:a,senderIdentityKey:u}})}const{tx:d}=await this.walletClient.createAction({description:r,outputs:n,options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1}},this.originator);if(null==d)throw new Error("Failed to create payment transaction");return{tx:d,outputs:s,description:r}}}function Gn(t){try{return"string"==typeof t?JSON.parse(t):t}catch(e){return zn("[PP CLIENT] Failed to parse input in safeParse:",t),{}}}const Xn="payment_inbox";class Yn extends Wn{peerPayWalletClient;_authFetchInstance;messageBox;constructor(t){const{messageBoxHost:e="https://messagebox.babbage.systems",walletClient:i,enableLogging:r=!1,originator:s}=t;super({host:e,walletClient:i,enableLogging:r,originator:s}),this.messageBox=t.messageBox??Xn,this.peerPayWalletClient=i,this.originator=s}get authFetchInstance(){return null!==this._authFetchInstance&&void 0!==this._authFetchInstance||(this._authFetchInstance=new os(this.peerPayWalletClient,void 0,void 0,this.originator)),this._authFetchInstance}async createPaymentToken(t){if(t.amount<=0)throw new Error("Invalid payment details: recipient and valid amount are required");const e=await Qr(this.peerPayWalletClient,"self",this.originator),i=await Qr(this.peerPayWalletClient,"self",this.originator);$n(`[PP CLIENT] Derivation Prefix: ${e}`),$n(`[PP CLIENT] Derivation Suffix: ${i}`);const{publicKey:r}=await this.peerPayWalletClient.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${e} ${i}`,counterparty:t.recipient},this.originator);if($n(`[PP CLIENT] Derived Public Key: ${r}`),null==r||""===r.trim())throw new Error("Failed to derive recipient’s public key");const s=(new Fi).lock($e.fromString(r).toAddress()).toHex();$n(`[PP CLIENT] Locking Script: ${s}`);const n=await this.peerPayWalletClient.createAction({description:"PeerPay payment",labels:["peerpay"],outputs:[{satoshis:t.amount,lockingScript:s,customInstructions:JSON.stringify({derivationPrefix:e,derivationSuffix:i,payee:t.recipient}),outputDescription:"Payment for PeerPay transaction"}],options:{randomizeOutputs:!1}},this.originator);if(void 0===n.tx)throw new Error("Transaction creation failed!");return $n("[PP CLIENT] Payment Action:",n),{customInstructions:{derivationPrefix:e,derivationSuffix:i},transaction:n.tx,amount:t.amount}}async sendPayment(t,e){if(null==t.recipient||""===t.recipient.trim()||t.amount<=0)throw new Error("Invalid payment details: recipient and valid amount are required");const i=await this.createPaymentToken(t);await this.sendMessage({recipient:t.recipient,messageBox:this.messageBox,body:JSON.stringify(i)},e)}async sendLivePayment(t,e){const i=await this.createPaymentToken(t);try{await this.sendLiveMessage({recipient:t.recipient,messageBox:this.messageBox,body:JSON.stringify(i)},e)}catch(r){jn("[PP CLIENT] sendLiveMessage failed, falling back to HTTP:",r),await this.sendMessage({recipient:t.recipient,messageBox:this.messageBox,body:JSON.stringify(i)},e)}}async listenForLivePayments({onPayment:t,overrideHost:e}){await this.listenForLiveMessages({messageBox:this.messageBox,overrideHost:e,onMessage:e=>{$n("[MB CLIENT] Received Live Payment:",e);const i={messageId:e.messageId,sender:e.sender,token:Gn(e.body)};$n("[PP CLIENT] Converted PeerMessage to IncomingPayment:",i),t(i)}})}async acceptPayment(t){try{$n(`[PP CLIENT] Processing payment: ${JSON.stringify(t,null,2)}`);const e=await this.peerPayWalletClient.internalizeAction({tx:t.token.transaction,outputs:[{paymentRemittance:{derivationPrefix:t.token.customInstructions.derivationPrefix,derivationSuffix:t.token.customInstructions.derivationSuffix,senderIdentityKey:t.sender},outputIndex:t.token.outputIndex??0,protocol:"wallet payment"}],labels:["peerpay"],description:"PeerPay Payment"},this.originator);return $n(`[PP CLIENT] Payment internalized successfully: ${JSON.stringify(e,null,2)}`),$n(`[PP CLIENT] Acknowledging payment with messageId: ${t.messageId}`),await this.acknowledgeMessage({messageIds:[t.messageId]}),{payment:t,paymentResult:e}}catch(t){return zn(`[PP CLIENT] Error accepting payment: ${String(t)}`),"Unable to receive payment!"}}async rejectPayment(t){if($n(`[PP CLIENT] Rejecting payment: ${JSON.stringify(t,null,2)}`),t.token.amount-1e3<1e3){$n("[PP CLIENT] Payment amount too small after fee, just acknowledging.");try{$n(`[PP CLIENT] Attempting to acknowledge message ${t.messageId}...`),null!==this.authFetch&&void 0!==this.authFetch||jn("[PP CLIENT] Warning: authFetch is undefined! Ensure PeerPayClient is initialized correctly."),$n("[PP CLIENT] authFetch instance:",this.authFetch),$n(`[PP CLIENT] Acknowledgment response: ${await this.acknowledgeMessage({messageIds:[t.messageId]})}`)}catch(t){if(null==t||"object"!=typeof t||!("message"in t)||"string"!=typeof t.message||!t.message.includes("401"))throw zn(`[PP CLIENT] Error acknowledging message: ${t.message}`),t;jn(`[PP CLIENT] Authentication issue while acknowledging: ${t.message}`)}}else{$n("[PP CLIENT] Accepting payment before refunding..."),await this.acceptPayment(t),$n(`[PP CLIENT] Sending refund of ${t.token.amount-1e3} to ${t.sender}...`),await this.sendPayment({recipient:t.sender,amount:t.token.amount-1e3}),$n("[PP CLIENT] Payment successfully rejected and refunded.");try{$n(`[PP CLIENT] Acknowledging message ${t.messageId} after refunding...`),await this.acknowledgeMessage({messageIds:[t.messageId]}),$n("[PP CLIENT] Acknowledgment after refund successful.")}catch(t){zn(`[PP CLIENT] Error acknowledging message after refund: ${t.message}`)}}}async listIncomingPayments(t){return(await this.listMessages({messageBox:this.messageBox,host:t})).map(t=>{const e=Gn(t.body);return{messageId:t.messageId,sender:t.sender,token:e}})}}return e})());
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.messageBoxClient=e():t.messageBoxClient=e()}(this,()=>(()=>{"use strict";var t={d:(e,i)=>{for(var r in i)t.o(i,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:i[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{MessageBoxClient:()=>Wn,PeerPayClient:()=>Yn,RemittanceAdapter:()=>Jn,STANDARD_PAYMENT_MESSAGEBOX:()=>Xn});var i={};t.r(i),t.d(i,{Decoder:()=>Cn,Encoder:()=>On,PacketType:()=>Nn,protocol:()=>An});const r="undefined"!=typeof globalThis?globalThis.Buffer:void 0,s=null!=r&&"function"==typeof r.from,n=new Int8Array(256).fill(-1);for(let t=0;t<10;t++)n[48+t]=t;for(let t=0;t<6;t++)n[65+t]=10+t,n[97+t]=10+t;class a{static zeros=["","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"];static groupSizes=[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];static groupBases=[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];static wordSize=26;static WORD_SIZE_BIGINT=BigInt(a.wordSize);static WORD_MASK=(1n<<a.WORD_SIZE_BIGINT)-1n;static MAX_SAFE_INTEGER_BIGINT=BigInt(Number.MAX_SAFE_INTEGER);static MIN_SAFE_INTEGER_BIGINT=BigInt(Number.MIN_SAFE_INTEGER);static MAX_IMULN_ARG=67108863;static MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT=(1n<<53n)-1n;_magnitude;_sign;_nominalWordLength;red;get negative(){return this._sign}set negative(t){this.assert(0===t||1===t,"Negative property must be 0 or 1");const e=1===t?1:0;0n===this._magnitude?this._sign=0:this._sign=e}get _computedWordsArray(){if(0n===this._magnitude)return[0];const t=[];let e=this._magnitude;for(;e>0n;)t.push(Number(e&a.WORD_MASK)),e>>=a.WORD_SIZE_BIGINT;return t.length>0?t:[0]}get words(){const t=this._computedWordsArray;if(this._nominalWordLength<=t.length)return t;const e=new Array(this._nominalWordLength).fill(0);for(let i=0;i<t.length;i++)e[i]=t[i];return e}set words(t){const e=this._sign;let i=0n;const r=t.length>0?t.length:1;for(let e=r-1;e>=0;e--){const r=void 0===t[e]?0:t[e];i=i<<a.WORD_SIZE_BIGINT|BigInt(r&Number(a.WORD_MASK))}this._magnitude=i,this._sign=e,this._nominalWordLength=r,this.normSign()}get length(){return Math.max(1,this._nominalWordLength)}static isBN(t){return t instanceof a||null!==t&&"object"==typeof t&&t.constructor?.wordSize===a.wordSize&&Array.isArray(t.words)}static max(t,e){return t.cmp(e)>0?t:e}static min(t,e){return t.cmp(e)<0?t:e}constructor(t=0,e=10,i="be"){if(this._magnitude=0n,this._sign=0,this._nominalWordLength=1,this.red=null,void 0===t&&(t=0),null===t)return void this._initializeState(0n,0);if("bigint"==typeof t)return this._initializeState(t<0n?-t:t,t<0n?1:0),void this.normSign();let r=e,s=i;if("le"!==e&&"be"!==e||(s=e,r=10),"number"!=typeof t)if(Array.isArray(t))this.initArray(t,s);else if("string"==typeof t){"hex"===r&&(r=16),this.assert("number"==typeof r&&r===(0|r)&&r>=2&&r<=36,"Base must be an integer between 2 and 36");const e=t.toString().replace(/\s+/g,"");let i=0,n=0;e.startsWith("-")?(i++,n=1):e.startsWith("+")&&i++;const a=e.substring(i);if(0===a.length)return this._initializeState(0n,1===n&&e.startsWith("-")?1:0),void this.normSign();if(16===r){let t;if("le"===s){const t=[];let e=a;e.length%2!=0&&(e="0"+e);for(let i=0;i<e.length;i+=2){const r=e.substring(i,i+2),s=parseInt(r,16);if(isNaN(s))throw new Error("Invalid character in "+e);t.push(s)}return this.initArray(t,"le"),this._sign=n,void this.normSign()}try{t=BigInt("0x"+a)}catch(t){throw new Error("Invalid character in "+a)}this._initializeState(t,n),this.normSign()}else try{if(this._parseBaseString(a,r),this._sign=n,this.normSign(),"le"===s){const t=this._sign;this.initArray(this.toArray("be"),"le"),this._sign=t,this.normSign()}}catch(t){const e=t;if(e.message.includes("Invalid character in string")||e.message.includes("Invalid digit for base")||e.message.startsWith("Invalid character:"))throw new Error("Invalid character");throw e}}else 0!==t?this.assert(!1,"Unsupported input type for BigNumber constructor"):this._initializeState(0n,0);else this.initNumber(t,s)}_bigIntToStringInBase(t,e){if(0n===t)return"0";if(e<2||e>36)throw new Error("Base must be between 2 and 36");let i="",r=t>0n?t:-t;const s=BigInt(e);for(;r>0n;)i="0123456789abcdefghijklmnopqrstuvwxyz"[Number(r%s)]+i,r/=s;return i}_parseBaseString(t,e){if(0===t.length)return this._magnitude=0n,void this._finishInitialization();this._magnitude=0n;const i=BigInt(e);let r=a.groupSizes[e],s=BigInt(a.groupBases[e]);0!==r&&0n!==s||(r=Math.floor(Math.log(67108863)/Math.log(e)),0===r&&(r=1),s=i**BigInt(r));let n=0;const o=t.length;let c=o%r;if(0===c&&o>0&&(c=r),c>0){const i=t.substring(n,n+c);this._magnitude=BigInt(this._parseBaseWord(i,e)),n+=c}for(;n<o;){const i=t.substring(n,n+r),a=BigInt(this._parseBaseWord(i,e));this._magnitude=this._magnitude*s+a,n+=r}this._finishInitialization()}_parseBaseWord(t,e){let i=0;for(let r=0;r<t.length;r++){const s=t.charCodeAt(r);let n;if(s>=48&&s<=57)n=s-48;else if(s>=65&&s<=90)n=s-65+10;else{if(!(s>=97&&s<=122))throw new Error("Invalid character: "+t[r]);n=s-97+10}if(n>=e)throw new Error("Invalid character");i=i*e+n}return i}_initializeState(t,e){this._magnitude=t,this._sign=0n===t?0:e,this._finishInitialization()}_finishInitialization(){if(0n===this._magnitude)this._nominalWordLength=1,this._sign=0;else{const t=this._magnitude.toString(2).length;this._nominalWordLength=Math.max(1,Math.ceil(t/a.wordSize))}}assert(t,e="Assertion failed"){if(!t)throw new Error(e)}initNumber(t,e="be"){if(this.assert(BigInt(Math.abs(t))<=a.MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT,"The number is larger than 2 ^ 53 (unsafe)"),this.assert(t%1==0,"Number must be an integer for BigNumber conversion"),this._initializeState(BigInt(Math.abs(t)),t<0?1:0),"le"===e){const t=this._sign,e=this.toArray("be");this.initArray(e,"le"),this._sign=t,this.normSign()}return this}initArray(t,e){if(0===t.length)return this._initializeState(0n,0),this;let i=0n;if("be"===e)for(let e=0;e<t.length;e++)i=i<<8n|BigInt(255&t[e]);else for(let e=t.length-1;e>=0;e--)i=i<<8n|BigInt(255&t[e]);return this._initializeState(i,0),this}copy(t){t._magnitude=this._magnitude,t._sign=this._sign,t._nominalWordLength=this._nominalWordLength,t.red=this.red}static move(t,e){t._magnitude=e._magnitude,t._sign=e._sign,t._nominalWordLength=e._nominalWordLength,t.red=e.red}clone(){const t=new a(0n);return this.copy(t),t}expand(t){return this.assert(t>=0,"Expand size must be non-negative"),this._nominalWordLength=Math.max(this._nominalWordLength,t,1),this}strip(){return this._finishInitialization(),this.normSign()}normSign(){return 0n===this._magnitude&&(this._sign=0),this}inspect(){return(null!==this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}_getMinimalHex(){return 0n===this._magnitude?"0":this._magnitude.toString(16)}toString(t=10,e=1){if(16===t||"hex"===t){let t=this._getMinimalHex();if(e>1)for("0"!==t&&t.length%2!=0&&(t="0"+t);t.length%e!==0;)t="0"+t;return(this.isNeg()?"-":"")+t}if("number"!=typeof t||t<2||t>36||t%1!=0)throw new Error("Base should be an integer between 2 and 36");return this.toBaseString(t,e)}toBaseString(t,e){if(0n===this._magnitude){let t="0";if(e>1)for(;t.length<e;)t="0"+t;return t}let i=a.groupSizes[t],r=BigInt(a.groupBases[t]);0!==i&&0n!==r||(i=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(t)),0===i&&(i=1),r=BigInt(t)**BigInt(i));let s="",n=this._magnitude;for(;n>0n;){const e=n%r;n/=r;const o=this._bigIntToStringInBase(e,t);if(n>0n){const t=i-o.length;s=t>0&&t<a.zeros.length?a.zeros[t]+o+s:t>0?"0".repeat(t)+o+s:o+s}else s=o+s}if(e>0)for(;s.length<e;)s="0"+s;return(1===this._sign?"-":"")+s}toNumber(){const t=this._getSignedValue();if(t>a.MAX_SAFE_INTEGER_BIGINT||t<a.MIN_SAFE_INTEGER_BIGINT)throw new Error("Number can only safely store up to 53 bits");return Number(t)}toBigInt(){return this._getSignedValue()}toJSON(){const t=this._getMinimalHex();return(this.isNeg()?"-":"")+t}toArrayLikeGeneric(t,e){let i=this._magnitude,r=e?0:t.length-1;const s=e?1:-1;for(let e=0;e<t.length;++e){if(0n===i&&r>=0&&r<t.length)t[r]=0;else{if(!(r>=0&&r<t.length))break;t[r]=Number(0xffn&i)}i>>=8n,r+=s}}toArray(t="be",e){this.strip();const i=this.byteLength(),r=e??Math.max(1,i);this.assert(i<=r,"byte array longer than desired length"),this.assert(r>0,"Requested array length <= 0");const s=new Array(r).fill(0);return 0n===this._magnitude&&r>0?s:0n===this._magnitude&&0===r?[]:(this.toArrayLikeGeneric(s,"le"===t),s)}bitLength(){return 0n===this._magnitude?0:this._magnitude.toString(2).length}static toBitArray(t){const e=t.bitLength();if(0===e)return[];const i=new Array(e),r=t._magnitude;for(let t=0;t<e;t++)i[t]=0n!=(r>>BigInt(t)&1n)?1:0;return i}toBitArray(){return a.toBitArray(this)}zeroBits(){if(0n===this._magnitude)return 0;let t=0,e=this._magnitude;for(;0n==(1n&e)&&0n!==e;)t++,e>>=1n;return t}byteLength(){return 0n===this._magnitude?0:Math.ceil(this.bitLength()/8)}_getSignedValue(){return 1===this._sign?-this._magnitude:this._magnitude}_setValueFromSigned(t){t<0n?(this._magnitude=-t,this._sign=1):(this._magnitude=t,this._sign=0),this._finishInitialization(),this.normSign()}toTwos(t){this.assert(t>=0);const e=BigInt(t);let i=this._getSignedValue();1===this._sign&&0n!==this._magnitude&&(i=(1n<<e)+i),i&=(1n<<e)-1n;const r=new a(0n);return r._initializeState(i,0),r}fromTwos(t){this.assert(t>=0);const e=BigInt(t),i=this._magnitude;if(t>0&&0n!=(i>>e-1n&1n)&&0===this._sign){const t=i-(1n<<e),r=new a(0n);return r._setValueFromSigned(t),r}return this.clone()}isNeg(){return 1===this._sign&&0n!==this._magnitude}neg(){return this.clone().ineg()}ineg(){return 0n!==this._magnitude&&(this._sign=1===this._sign?0:1),this}_iuop(t,e){const i=e(this._magnitude,t._magnitude),r=e===((t,e)=>t^e);let s=this._nominalWordLength;return r&&(s=Math.max(this.length,t.length)),this._magnitude=i,this._finishInitialization(),r&&(this._nominalWordLength=Math.max(this._nominalWordLength,s)),this.strip()}iuor(t){return this._iuop(t,(t,e)=>t|e)}iuand(t){return this._iuop(t,(t,e)=>t&e)}iuxor(t){return this._iuop(t,(t,e)=>t^e)}_iop(t,e){return this.assert(0===this._sign&&0===t._sign),this._iuop(t,e)}ior(t){return this._iop(t,(t,e)=>t|e)}iand(t){return this._iop(t,(t,e)=>t&e)}ixor(t){return this._iop(t,(t,e)=>t^e)}_uop_new(t,e){return this.length>=t.length?this.clone()[e](t):t.clone()[e](this)}or(t){return this.assert(0===this._sign&&0===t._sign),this._uop_new(t,"iuor")}uor(t){return this._uop_new(t,"iuor")}and(t){return this.assert(0===this._sign&&0===t._sign),this._uop_new(t,"iuand")}uand(t){return this._uop_new(t,"iuand")}xor(t){return this.assert(0===this._sign&&0===t._sign),this._uop_new(t,"iuxor")}uxor(t){return this._uop_new(t,"iuxor")}inotn(t){this.assert("number"==typeof t&&t>=0);const e=(1n<<BigInt(t))-1n;this._magnitude=~this._magnitude&e;const i=0===t?1:Math.ceil(t/a.wordSize);return this._nominalWordLength=Math.max(1,i),this.strip(),this._nominalWordLength=Math.max(this._nominalWordLength,Math.max(1,i)),this}notn(t){return this.clone().inotn(t)}setn(t,e){this.assert("number"==typeof t&&t>=0);const i=BigInt(t);1===e||!0===e?this._magnitude|=1n<<i:this._magnitude&=~(1n<<i);const r=Math.floor(t/a.wordSize)+1;return this._nominalWordLength=Math.max(this._nominalWordLength,r),this._finishInitialization(),this.strip()}iadd(t){return this._setValueFromSigned(this._getSignedValue()+t._getSignedValue()),this}add(t){const e=new a(0n);return e._setValueFromSigned(this._getSignedValue()+t._getSignedValue()),e}isub(t){return this._setValueFromSigned(this._getSignedValue()-t._getSignedValue()),this}sub(t){const e=new a(0n);return e._setValueFromSigned(this._getSignedValue()-t._getSignedValue()),e}mul(t){const e=new a(0n);return e._magnitude=this._magnitude*t._magnitude,e._sign=0n===e._magnitude?0:this._sign^t._sign,e._nominalWordLength=this.length+t.length,e.red=null,e.normSign()}imul(t){return this._magnitude*=t._magnitude,this._sign=0n===this._magnitude?0:this._sign^t._sign,this._nominalWordLength=this.length+t.length,this.red=null,this.normSign()}imuln(t){return this.assert("number"==typeof t,"Assertion failed"),this.assert(Math.abs(t)<=a.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()*BigInt(t)),this}muln(t){return this.clone().imuln(t)}sqr(){const t=new a(0n);return t._magnitude=this._magnitude*this._magnitude,t._sign=0,t._nominalWordLength=2*this.length,t.red=null,t}isqr(){return this._magnitude*=this._magnitude,this._sign=0,this._nominalWordLength=2*this.length,this.red=null,this}pow(t){if(this.assert(0===t._sign,"Exponent for pow must be non-negative"),t.isZero())return new a(1n);const e=new a(1n),i=this.clone(),r=t.clone(),s=i.isNeg(),n=r.isOdd();for(s&&i.ineg();!r.isZero();)r.isOdd()&&e.imul(i),i.isqr(),r.iushrn(1);return s&&n&&e.ineg(),e}static normalizeNonNegativeBigInt(t,e){if("number"==typeof t){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return BigInt(t)}if(t<0n)throw new Error(`${e} must be a non-negative integer`);return t}iushln(t){const e=a.normalizeNonNegativeBigInt(t,"Shift bits");return 0n===e?this:(this._magnitude<<=e,this._finishInitialization(),this.strip())}ishln(t){return this.assert(0===this._sign,"ishln requires positive number"),this.iushln(t)}iushrn(t,e,i){const r=a.normalizeNonNegativeBigInt(t,"Shift bits");if(0n===r)return null!=i&&i._initializeState(0n,0),this;if(null!=i){const t=(1n<<r)-1n,e=this._magnitude&t;i._initializeState(e,0)}return this._magnitude>>=r,this._finishInitialization(),this.strip()}ishrn(t,e,i){return this.assert(0===this._sign,"ishrn requires positive number"),this.iushrn(t,e,i)}shln(t){return this.clone().ishln(t)}ushln(t){return this.clone().iushln(t)}shrn(t){return this.clone().ishrn(t)}ushrn(t){return this.clone().iushrn(t)}testn(t){return this.assert("number"==typeof t&&t>=0),0n!=(this._magnitude>>BigInt(t)&1n)}imaskn(t){this.assert("number"==typeof t&&t>=0),this.assert(0===this._sign,"imaskn works only with positive numbers");const e=BigInt(t),i=0n===e?0n:(1n<<e)-1n;this._magnitude&=i;const r=0===t?1:Math.max(1,Math.ceil(t/a.wordSize));return this._nominalWordLength=r,this._finishInitialization(),this._nominalWordLength=Math.max(this._nominalWordLength,r),this.strip()}maskn(t){return this.clone().imaskn(t)}iaddn(t){return this.assert("number"==typeof t),this.assert(Math.abs(t)<=a.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()+BigInt(t)),this}_iaddn(t){return this.iaddn(t)}isubn(t){return this.assert("number"==typeof t),this.assert(Math.abs(t)<=a.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()-BigInt(t)),this}addn(t){return this.clone().iaddn(t)}subn(t){return this.clone().isubn(t)}iabs(){return this._sign=0,this}abs(){return this.clone().iabs()}divmod(t,e,i){if(this.assert(!t.isZero(),"Division by zero"),this.isZero()){const t=new a(0n);return{div:"mod"!==e?t:null,mod:"div"!==e?t:null}}const r=this._getSignedValue(),s=t._getSignedValue();let n=null,o=null;"mod"!==e&&(n=r/s),"div"!==e&&(o=r%s,!0===i&&o<0n&&(o+=s<0n?-s:s));const c=null!==n?new a(0n):null;null!==c&&null!==n&&c._setValueFromSigned(n);const h=null!==o?new a(0n):null;return null!==h&&null!==o&&h._setValueFromSigned(o),{div:c,mod:h}}div(t){return this.divmod(t,"div",!1).div}mod(t){return this.divmod(t,"mod",!1).mod}umod(t){return this.divmod(t,"mod",!0).mod}divRound(t){this.assert(!t.isZero());const e=this._getSignedValue(),i=t._getSignedValue();let r=e/i;const s=e%i;if(0n===s){const t=new a(0n);return t._setValueFromSigned(r),t}2n*(s<0n?-s:s)>=(i<0n?-i:i)&&(e>0n&&i>0n||e<0n&&i<0n?r+=1n:r-=1n);const n=new a(0n);return n._setValueFromSigned(r),n}modrn(t){this.assert(0!==t,"Division by zero in modrn");const e=BigInt(Math.abs(t));if(0n===e)throw new Error("Division by zero in modrn");const i=this._magnitude%e;return Number(t<0?-i:i)}idivn(t){return this.assert(0!==t),this.assert(Math.abs(t)<=a.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()/BigInt(t)),this}divn(t){return this.clone().idivn(t)}egcd(t){this.assert(0===t._sign,"p must not be negative"),this.assert(!t.isZero(),"p must not be zero");let e=this._getSignedValue(),i=t._magnitude,r=1n,s=0n,n=0n,o=1n;for(;0n!==i;){const t=e/i;let a=i;i=e%i,e=a,a=s,s=r-t*s,r=a,a=o,o=n-t*o,n=a}const c=new a(0n);c._setValueFromSigned(r);const h=new a(0n);h._setValueFromSigned(n);const u=new a(0n);return u._initializeState(e<0n?-e:e,0),{a:c,b:h,gcd:u}}gcd(t){let e=this._magnitude,i=t._magnitude;if(0n===e){const t=new a(0n);return t._setValueFromSigned(i),t.iabs()}if(0n===i){const t=new a(0n);return t._setValueFromSigned(e),t.iabs()}for(;0n!==i;){const t=e%i;e=i,i=t}const r=new a(0n);return r._initializeState(e,0),r}invm(t){this.assert(!t.isZero()&&0===t._sign,"Modulus for invm must be positive and non-zero");const e=this.egcd(t);if(!e.gcd.eqn(1))throw new Error("Inverse does not exist (numbers are not coprime).");return e.a.umod(t)}isEven(){return this._magnitude%2n==0n}isOdd(){return this._magnitude%2n==1n}andln(t){return this.assert(t>=0),Number(this._magnitude&BigInt(t))}bincn(t){this.assert("number"==typeof t&&t>=0);const e=1n<<BigInt(t);return this._setValueFromSigned(this._getSignedValue()+e),this}isZero(){return 0n===this._magnitude}cmpn(t){this.assert(Math.abs(t)<=a.MAX_IMULN_ARG,"Number is too big");const e=this._getSignedValue(),i=BigInt(t);return e<i?-1:e>i?1:0}cmp(t){const e=this._getSignedValue(),i=t._getSignedValue();return e<i?-1:e>i?1:0}ucmp(t){return this._magnitude<t._magnitude?-1:this._magnitude>t._magnitude?1:0}gtn(t){return 1===this.cmpn(t)}gt(t){return 1===this.cmp(t)}gten(t){return this.cmpn(t)>=0}gte(t){return this.cmp(t)>=0}ltn(t){return-1===this.cmpn(t)}lt(t){return-1===this.cmp(t)}lten(t){return this.cmpn(t)<=0}lte(t){return this.cmp(t)<=0}eqn(t){return 0===this.cmpn(t)}eq(t){return 0===this.cmp(t)}toRed(t){return this.assert(null==this.red,"Already a number in reduction context"),this.assert(0===this._sign,"toRed works only with positives"),t.convertTo(this).forceRed(t)}fromRed(){return this.assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(t){return this.red=t,this}redAdd(t){return this.assert(this.red,"redAdd works only with red numbers"),this.red.add(this,t)}redIAdd(t){return this.assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)}redSub(t){return this.assert(this.red,"redSub works only with red numbers"),this.red.sub(this,t)}redISub(t){return this.assert(this.red,"redISub works only with red numbers"),this.red.isub(this,t)}redShl(t){return this.assert(this.red,"redShl works only with red numbers"),this.red.shl(this,t)}redMul(t){return this.assert(this.red,"redMul works only with red numbers"),this.red.verify2(this,t),this.red.mul(this,t)}redIMul(t){return this.assert(this.red,"redIMul works only with red numbers"),this.red.verify2(this,t),this.red.imul(this,t)}redSqr(){return this.assert(this.red,"redSqr works only with red numbers"),this.red.verify1(this),this.red.sqr(this)}redISqr(){return this.assert(this.red,"redISqr works only with red numbers"),this.red.verify1(this),this.red.isqr(this)}redSqrt(){return this.assert(this.red,"redSqrt works only with red numbers"),this.red.verify1(this),this.red.sqrt(this)}redInvm(){return this.assert(this.red,"redInvm works only with red numbers"),this.red.verify1(this),this.red.invm(this)}redNeg(){return this.assert(this.red,"redNeg works only with red numbers"),this.red.verify1(this),this.red.neg(this)}redPow(t){return this.assert(null!=this.red&&null==t.red,"redPow(normalNum)"),this.red.verify1(this),this.red.pow(this,t)}static fromHex(t,e){let i="be";return"little"!==e&&"le"!==e||(i="le"),new a(t,16,i)}toHex(t=0){if(this.isZero()&&0===t)return"";let e=this._getMinimalHex();"0"!==e&&e.length%2!=0&&(e="0"+e);const i=2*t;for(;e.length<i;)e="0"+e;return(this.isNeg()?"-":"")+e}static fromJSON(t){return new a(t,16)}static fromNumber(t){return new a(t)}static fromString(t,e){return new a(t,e)}static fromSm(t,e="big"){if(0===t.length)return new a(0n);const i=t.slice();"little"===e&&i.reverse();let n=0;i.length>0&&128&i[0]&&(n=1,i[0]&=127);let o=0n;if(s){const t=r.from(i).toString("hex");o=0===t.length?0n:BigInt("0x"+t)}else{let t="";for(const e of i)t+=e<16?"0"+e.toString(16):e.toString(16);o=0===t.length?0n:BigInt("0x"+t)}const c=new a(0n);return c._initializeState(o,n),c}toSm(t="big"){if(0n===this._magnitude)return 1===this._sign?[128]:[];let e=this._getMinimalHex();e.length%2!=0&&(e="0"+e);const i=e.length/2,r=new Array(i);for(let t=0,i=0;t<e.length;t+=2){const s=n[e.charCodeAt(t)],a=n[e.charCodeAt(t+1)];r[i++]=(15&s)<<4|15&a}let s;return 1===this._sign?128&r[0]?s=[128,...r]:(s=r.slice(),s[0]|=128):s=128&r[0]?[0,...r]:r.slice(),"little"===t?s.reverse():s}static fromBits(t,e=!1){const i=t>>>24,r=8388607&t,s=!!(8388608&t);if(e&&s)throw new Error("negative bit set");if(0===i&&0===r){if(s&&e)throw new Error("negative bit set for zero value");return new a(0n)}const n=new a(r);return i<=3?n.iushrn(8*(3-i)):n.iushln(8*(i-3)),s&&n.ineg(),n}toBits(){if(this.strip(),this.isZero()&&!this.isNeg())return 0;const t=this.isNeg(),e=this.abs();let i=e.toArray("be"),r=0;for(;r<i.length-1&&0===i[r];)r++;i=i.slice(r);let s,n=i.length;if(0!==n||e.isZero()||(i=[0],n=1),e.isZero()&&(n=0,i=[]),0===n)s=0;else if(n<=3){s=0;for(let t=0;t<n;t++)s=s<<8|i[t]}else s=i[0]<<16|i[1]<<8|i[2];8388608&s&&n<=255&&(s>>>=8,n++);let a=n<<24|s;return t&&(a|=8388608),a>>>0}static fromScriptNum(t,e=!1,i){if(void 0!==i&&t.length>i)throw new Error("script number overflow");if(0===t.length)return new a(0n);if(e&&!(127&t[t.length-1]||!(t.length<=1)&&128&t[t.length-2]))throw new Error("non-minimally encoded script number");return a.fromSm(t,"little")}toScriptNum(){return this.toSm("little")}_invmp(t){this.assert(0===t._sign,"p must not be negative for _invmp"),this.assert(!t.isZero(),"p must not be zero for _invmp");const e=this.umod(t),i=t.subn(2);if(null!==e.red)return e.redPow(i);let r=new a(1n),s=e.clone();const n=i.clone();for(;!n.isZero();)n.isOdd()&&(r=r.mul(s).umod(t)),s=s.sqr().umod(t),n.iushrn(1);return r}mulTo(t,e){return e._magnitude=this._magnitude*t._magnitude,e._sign=0n===e._magnitude?0:this._sign^t._sign,e._nominalWordLength=this.length+t.length,e.red=null,e.normSign(),e}}class o{name;p;k;n;tmp;constructor(t,e){this.name=t,this.p=new a(e,16),this.n=this.p.bitLength(),this.k=new a(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){const t=new a(BigInt(0)),e=Math.ceil(this.n/a.wordSize);return t.expand(Math.max(1,e)),t}ireduce(t){const e=t;let i;do{this.split(e,this.tmp),this.imulK(e),e.iadd(this.tmp),i=e.bitLength()}while(i>this.n);const r=i<this.n?-1:e.ucmp(this.p);return 0===r?e.words=[0]:r>0&&e.isub(this.p),e.strip(),e}split(t,e){t.iushrn(this.n,0,e)}imulK(t){return t.imul(this.k)}}class c extends o{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(t,e){const i=4194303,r=t.words,s=t.length,n=Math.min(s,9),a=new Array(n+(s>9?1:0)).fill(0);for(let t=0;t<n;t++)a[t]=r[t];let o=n;if(s<=9){const i=new Array(o);for(let t=0;t<o;++t)i[t]=a[t];return e.words=i,void(t.words=[0])}let c=r[9];a[o++]=c&i;const h=new Array(o);for(let t=0;t<o;++t)h[t]=a[t];e.words=h;const u=new Array(Math.max(1,s-9)).fill(0);let d=0;for(let t=10;t<s;t++){const e=0|r[t];d<u.length&&(u[d++]=(e&i)<<4|c>>>22),c=e}c>>>=22,d<u.length?u[d++]=c:0!==c&&u.length;const l=new Array(d);for(let t=0;t<d;++t)l[t]=u[t];t.words=l}imulK(t){const e=t.words,i=t.length,r=i+2,s=new Array(r).fill(0);for(let t=0;t<i;t++)s[t]=e[t];let n=0;for(let t=0;t<r;t++){const e=0|s[t];n+=977*e,s[t]=67108863&n,n=64*e+(n/67108864|0)}return t.words=s,t}}class h{prime;m;constructor(t){if("k256"===t){const t=new c;this.m=t.p,this.prime=t}else this.assert(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}assert(t,e="Assertion failed"){if(!t)throw new Error(e)}verify1(t){this.assert(0===t.negative,"red works only with positives"),this.assert(t.red,"red works only with red numbers")}verify2(t,e){this.assert(0===(t.negative|e.negative),"red works only with positives"),this.assert(null!=t.red&&t.red===e.red,"red works only with red numbers")}imod(t){return null!=this.prime?this.prime.ireduce(t).forceRed(this):(a.move(t,t.umod(this.m).forceRed(this)),t)}neg(t){return t.isZero()?t.clone():this.m.sub(t).forceRed(this)}add(t,e){this.verify2(t,e);const i=t.clone();return i.iadd(e),i.isub(this.m),i.isNeg()&&i.iadd(this.m),i}iadd(t,e){return this.verify2(t,e),t.iadd(e),t.isub(this.m),t.isNeg()&&t.iadd(this.m),t}sub(t,e){this.verify2(t,e);const i=t.sub(e);return i.cmpn(0)<0&&i.iadd(this.m),i.forceRed(this)}isub(t,e){this.verify2(t,e);const i=t.isub(e);return i.cmpn(0)<0&&i.iadd(this.m),i}shl(t,e){return this.verify1(t),this.imod(t.ushln(e))}imul(t,e){return this.verify2(t,e),this.imod(t.imul(e))}mul(t,e){return this.verify2(t,e),this.imod(t.mul(e))}isqr(t){return this.imul(t,t.clone())}sqr(t){return this.mul(t,t)}sqrt(t){if(t.isZero())return t.clone();const e=this.m.andln(3);if(this.assert(e%2==1),3===e){const e=this.m.add(new a(1)).iushrn(2);return this.pow(t,e)}const i=this.m.subn(1);let r=0;for(;!i.isZero()&&0===i.andln(1);)r++,i.iushrn(1);this.assert(!i.isZero());const s=new a(1).toRed(this),n=s.redNeg(),o=this.m.subn(1).iushrn(1),c=this.m.bitLength(),h=new a(2*c*c).toRed(this);for(;0!==this.pow(h,o).cmp(n);)h.redIAdd(n);let u=this.pow(h,i),d=this.pow(t,i.addn(1).iushrn(1)),l=this.pow(t,i),f=r;for(;0!==l.cmp(s);){let t=l,e=0;for(;0!==t.cmp(s);e++)t=t.redSqr();this.assert(e<f);const i=this.pow(u,new a(1).iushln(f-e-1));d=d.redMul(i),u=i.redSqr(),l=l.redMul(u),f=e}return d}invm(t){const e=t._invmp(this.m);return 0!==e.negative?(e.negative=0,this.imod(e).redNeg()):this.imod(e)}pow(t,e){if(this.verify1(t),e.isZero())return new a(1).toRed(this);let i=new a(1).toRed(this);const r=t.clone();for(let t=e.bitLength()-1;t>=0;t--)i=this.sqr(i),e.testn(t)&&(i=this.mul(i,r));return i}convertTo(t){const e=t.umod(this.m);return e===t?e.clone():e}convertFrom(t){const e=t.clone();return e.red=null,e}}class u extends h{shift;r;r2;rinv;minv;constructor(t){super(t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new a(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)}convertTo(t){return this.imod(t.ushln(this.shift))}convertFrom(t){const e=this.imod(t.mul(this.rinv));return e.red=null,e}imul(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;const i=t.imul(e),r=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),s=i.isub(r).iushrn(this.shift);let n=s;return s.cmp(this.m)>=0?n=s.isub(this.m):s.cmpn(0)<0&&(n=s.iadd(this.m)),n.forceRed(this)}mul(t,e){if(t.isZero()||e.isZero())return new a(0).forceRed(this);const i=t.mul(e),r=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),s=i.isub(r).iushrn(this.shift);let n=s;return s.cmp(this.m)>=0?n=s.isub(this.m):s.cmpn(0)<0&&(n=s.iadd(this.m)),n.forceRed(this)}invm(t){return this.imod(t._invmp(this.m).mul(this.r2)).forceRed(this)}}class d{curve;type;precomputed;constructor(t){this.curve=new Re,this.type=t,this.precomputed=null}}class l extends d{x;y;z;zOne;constructor(t,e,i){super("jacobian"),null===t&&null===e&&null===i?(this.x=this.curve.one,this.y=this.curve.one,this.z=new a(0)):(a.isBN(t)||(t=new a(t,16)),this.x=t,a.isBN(e)||(e=new a(e,16)),this.y=e,a.isBN(i)||(i=new a(i,16)),this.z=i),null==this.x.red&&(this.x=this.x.toRed(this.curve.red)),null==this.y.red&&(this.y=this.y.toRed(this.curve.red)),null==this.z.red&&(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.isInfinity()&&(this.x=this.curve.one,this.y=this.curve.one,this.z=new a(0).toRed(this.curve.red),this.zOne=!1)}toP(){if(this.isInfinity())return new Te(null,null);const t=this.z.redInvm(),e=t.redSqr(),i=this.x.redMul(e),r=this.y.redMul(e).redMul(t);return new Te(i,r)}neg(){return new l(this.x,this.y.redNeg(),this.z)}add(t){if(this.isInfinity())return t;if(t.isInfinity())return this;const e=t.z.redSqr(),i=this.z.redSqr(),r=this.x.redMul(e),s=t.x.redMul(i),n=this.y.redMul(e.redMul(t.z)),a=t.y.redMul(i.redMul(this.z)),o=r.redSub(s),c=n.redSub(a);if(0===o.cmpn(0))return 0!==c.cmpn(0)?new l(null,null,null):this.dbl();const h=o.redSqr(),u=h.redMul(o),d=r.redMul(h),f=c.redSqr().redIAdd(u).redISub(d).redISub(d),p=c.redMul(d.redISub(f)).redISub(n.redMul(u)),g=this.z.redMul(t.z).redMul(o);return new l(f,p,g)}mixedAdd(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;if(null===t.x||null===t.y)throw new Error("Point coordinates cannot be null");const e=this.z.redSqr(),i=this.x,r=t.x.redMul(e),s=this.y,n=t.y.redMul(e).redMul(this.z),a=i.redSub(r),o=s.redSub(n);if(0===a.cmpn(0))return 0!==o.cmpn(0)?new l(null,null,null):this.dbl();const c=a.redSqr(),h=c.redMul(a),u=i.redMul(c),d=o.redSqr().redIAdd(h).redISub(u).redISub(u),f=o.redMul(u.redISub(d)).redISub(s.redMul(h)),p=this.z.redMul(a);return new l(d,f,p)}dblp(t){if(0===t)return this;if(this.isInfinity())return this;if(void 0===t)return this.dbl();let e=this;for(let i=0;i<t;i++)e=e.dbl();return e}dbl(){if(this.isInfinity())return this;let t,e,i;if(this.zOne){const r=this.x.redSqr(),s=this.y.redSqr(),n=s.redSqr();let a=this.x.redAdd(s).redSqr().redISub(r).redISub(n);a=a.redIAdd(a);const o=r.redAdd(r).redIAdd(r),c=o.redSqr().redISub(a).redISub(a);let h=n.redIAdd(n);h=h.redIAdd(h),h=h.redIAdd(h),t=c,e=o.redMul(a.redISub(c)).redISub(h),i=this.y.redAdd(this.y)}else{const r=this.x.redSqr(),s=this.y.redSqr(),n=s.redSqr();let a=this.x.redAdd(s).redSqr().redISub(r).redISub(n);a=a.redIAdd(a);const o=r.redAdd(r).redIAdd(r),c=o.redSqr();let h=n.redIAdd(n);h=h.redIAdd(h),h=h.redIAdd(h),t=c.redISub(a).redISub(a),e=o.redMul(a.redISub(t)).redISub(h),i=this.y.redMul(this.z),i=i.redIAdd(i)}return new l(t,e,i)}eq(t){if("affine"===t.type)return this.eq(t.toJ());if(this===t)return!0;if(this.isInfinity()&&t.isInfinity())return!0;if(this.isInfinity()!==t.isInfinity())return!1;const e=this.z.redSqr(),i=t.z.redSqr();if(0!==this.x.redMul(i).redISub(t.x.redMul(e)).cmpn(0))return!1;const r=e.redMul(this.z),s=i.redMul(t.z);return 0===this.y.redMul(s).redISub(t.y.redMul(r)).cmpn(0)}eqXToP(t){const e=this.z.redSqr(),i=t.toRed(this.curve?.red).redMul(e);if(0===this.x.cmp(i))return!0;const r=t.clone();if(null===this.curve||null==this.curve.redN)throw new Error("Curve or redN is not initialized.");const s=this.curve.redN.redMul(e);for(;r.cmp(this.curve.p)<0;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(i.redIAdd(s),0===this.x.cmp(i))return!0}return!1}inspect(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"}isInfinity(){return 0===this.z.cmpn(0)}}const f=/^[0-9a-fA-F]*$/;function p(t){if("string"!=typeof t)throw new TypeError("Invalid hex string");if(0!==t.length&&!f.test(t))throw new Error("Invalid hex string")}const g=(t,e="Hash assertion failed")=>{if(!t)throw new Error(e)};class y{pending;pendingTotal;blockSize;outSize;endian;_delta8;_delta32;padLength;hmacStrength;constructor(t,e,i,r){this.pending=null,this.pendingTotal=0,this.blockSize=t,this.outSize=e,this.hmacStrength=i,this.padLength=r/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}_update(t,e){throw new Error("Not implemented")}_digest(){throw new Error("Not implemented")}_digestHex(){throw new Error("Not implemented")}update(t,e){if(t=m(t,e),null==this.pending?this.pending=t:this.pending=this.pending.concat(t),this.pendingTotal+=t.length,this.pending.length>=this._delta8){const e=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-e,t.length),0===this.pending.length&&(this.pending=null),t=function(t,e,i,r){const s=i-0;g(s%4==0);const n=new Array(s/4);for(let e=0,i=0;e<n.length;e++,i+=4){let s;s="big"===r?t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3]:t[i+3]<<24|t[i+2]<<16|t[i+1]<<8|t[i],n[e]=s>>>0}return n}(t,0,t.length-e,this.endian);for(let e=0;e<t.length;e+=this._delta32)this._update(t,e)}return this}digest(){return this.update(this._pad()),g(null===this.pending),this._digest()}digestHex(){return this.update(this._pad()),g(null===this.pending),this._digestHex()}_pad(){const t=this.pendingTotal;if(!Number.isSafeInteger(t)||t<0)throw new Error("Message too long for this hash function");const e=this._delta8,i=e-(t+this.padLength)%e,r=new Array(i+this.padLength);let s;for(r[0]=128,s=1;s<i;s++)r[s]=0;const n=this.padLength,a=1n<<BigInt(8*n);let o=8n*BigInt(t);if(o>=a)throw new Error("Message too long for this hash function");if("big"===this.endian){const t=new Array(n);for(let e=n-1;e>=0;e--)t[e]=Number(0xffn&o),o>>=8n;for(let e=0;e<n;e++)r[s++]=t[e]}else for(let t=0;t<n;t++)r[s++]=Number(0xffn&o),o>>=8n;return r}}function b(t,e){return 55296==(64512&t.charCodeAt(e))&&!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1))}function m(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];const i=[];if("string"==typeof t)if("hex"!==e){let e=0;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);s<128?i[e++]=s:s<2048?(i[e++]=s>>6|192,i[e++]=63&s|128):b(t,r)?(s=65536+((1023&s)<<10)+(1023&t.charCodeAt(++r)),i[e++]=s>>18|240,i[e++]=s>>12&63|128,i[e++]=s>>6&63|128,i[e++]=63&s|128):(i[e++]=s>>12|224,i[e++]=s>>6&63|128,i[e++]=63&s|128)}}else{p(t),t=function(t){if(p(t),0===t.length)return"";let e=t.toLowerCase();return e.length%2!=0&&(e="0"+e),e}(t);for(let e=0;e<t.length;e+=2)i.push(parseInt(t[e]+t[e+1],16))}else for(let e=0;e<t.length;e++)i[e]=0|t[e];return i}function w(t){return function(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}(t)}function v(t,e){let i="";for(let r=0;r<t.length;r++){let s=t[r];"little"===e&&(s=w(s)),i+=I(s.toString(16))}return i}function I(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}function k(t){let e="";for(const i of t)e+=i.toString(16).padStart(2,"0");return e}function S(t,e){const i=new Array(4*t.length);for(let r=0,s=0;r<t.length;r++,s+=4){const n=t[r];"big"===e?(i[s]=n>>>24,i[s+1]=n>>>16&255,i[s+2]=n>>>8&255,i[s+3]=255&n):(i[s+3]=n>>>24,i[s+2]=n>>>16&255,i[s+1]=n>>>8&255,i[s]=255&n)}return i}function E(t,e){return t>>>e|t<<32-e}function x(t,e){return t<<e|t>>>32-e}function P(t,e){return t+e>>>0}function _(t,e,i){return t+e+i>>>0}function A(t,e,i,r){return t+e+i+r>>>0}function N(t,e,i,r,s){return t+e+i+r+s>>>0}function O(t,e,i,r){return 0===t?T(e,i,r):1===t||3===t?function(t,e,i){return t^e^i}(e,i,r):2===t?C(e,i,r):0}function T(t,e,i){return t&e^~t&i}function C(t,e,i){return t&e^t&i^e&i}function R(t){return E(t,2)^E(t,13)^E(t,22)}function B(t){return E(t,6)^E(t,11)^E(t,25)}function L(t){return E(t,7)^E(t,18)^t>>>3}function M(t){return E(t,17)^E(t,19)^t>>>10}const F=[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],U=[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],D=[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],H=[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];function q(t,e,i,r){return t<=15?e^i^r:t<=31?e&i|~e&r:t<=47?(e|~i)^r:t<=63?e&r|i&~r:e^(i|~r)}function V(t){return t<=15?0:t<=31?1518500249:t<=47?1859775393:t<=63?2400959708:2840853838}function K(t){return t<=15?1352829926:t<=31?1548603684:t<=47?1836072691:t<=63?2053994217:0}class $ extends y{h;constructor(){super(512,160,192,64),this.endian="little",this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}_update(t,e){let i,r=this.h[0],s=this.h[1],n=this.h[2],a=this.h[3],o=this.h[4],c=r,h=s,u=n,d=a,l=o;for(let f=0;f<80;f++)i=P(x(A(r,q(f,s,n,a),t[F[f]+e],V(f)),D[f]),o),r=o,o=a,a=x(n,10),n=s,s=i,i=P(x(A(c,q(79-f,h,u,d),t[U[f]+e],K(f)),H[f]),l),c=l,l=d,d=x(u,10),u=h,h=i;i=_(this.h[1],n,d),this.h[1]=_(this.h[2],a,l),this.h[2]=_(this.h[3],o,c),this.h[3]=_(this.h[4],r,h),this.h[4]=_(this.h[0],s,u),this.h[0]=i}_digest(){return S(this.h,"little")}_digestHex(){return v(this.h,"little")}}class j{h;constructor(){this.h=new At}update(t,e){const i=t instanceof Uint8Array?t:Uint8Array.from(m(t,e));return this.h.update(i),this}digest(){return Array.from(this.h.digest())}digestHex(){return k(this.h.digest())}}class z extends y{h;W;k;constructor(){super(512,160,80,64),this.k=[1518500249,1859775393,2400959708,3395469782],this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}_update(t,e){const i=this.W;let r;for(void 0===e&&(e=0),r=0;r<16;r++)i[r]=t[e+r];for(;r<i.length;r++)i[r]=x(i[r-3]^i[r-8]^i[r-14]^i[r-16],1);let s=this.h[0],n=this.h[1],a=this.h[2],o=this.h[3],c=this.h[4];for(r=0;r<i.length;r++){const t=~~(r/20),e=N(x(s,5),O(t,n,a,o),c,i[r],this.k[t]);c=o,o=a,a=x(n,30),n=s,s=e}this.h[0]=P(this.h[0],s),this.h[1]=P(this.h[1],n),this.h[2]=P(this.h[2],a),this.h[3]=P(this.h[3],o),this.h[4]=P(this.h[4],c)}_digest(){return S(this.h,"big")}_digestHex(){return v(this.h,"big")}}class W{h;blockSize=64;outSize=32;constructor(t){const e=t instanceof Uint8Array?t:Uint8Array.from(m(t,"string"==typeof t?"hex":void 0));this.h=new Ut(Nt,e)}update(t,e){const i=t instanceof Uint8Array?t:Uint8Array.from(m(t,e));return this.h.update(i),this}digest(){return Array.from(this.h.digest())}digestHex(){return k(this.h.digest())}}class G{h;blockSize=128;outSize=32;constructor(t){const e=t instanceof Uint8Array?t:Uint8Array.from(m(t,"string"==typeof t?"hex":void 0));this.h=new Ut(Ft,e)}update(t,e){const i=t instanceof Uint8Array?t:Uint8Array.from(m(t,e));return this.h.update(i),this}digest(){return Array.from(this.h.digest())}digestHex(){return k(this.h.digest())}}const X=(t,e)=>(new j).update(t,e).digest(),Y=(t,e)=>{const i=(new j).update(t,e).digest();return(new j).update(i).digest()},J=(t,e)=>{const i=(new j).update(t,e).digest();return(new $).update(i).digest()},Z=(t,e,i)=>new W(t).update(e,i).digest(),Q=(t,e,i)=>new G(t).update(e,i).digest();function tt(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, got ${t}`)}function et(t,...e){if(!((i=t)instanceof Uint8Array||ArrayBuffer.isView(i)&&"Uint8Array"===i.constructor.name))throw new Error("Uint8Array expected");var i;if(e.length>0&&!e.includes(t.length)){const i=e.join(",");throw new Error(`Uint8Array expected of length ${i}, got length=${t.length}`)}}function it(t,e=!0){if(!0===t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&!0===t.finished)throw new Error("Hash#digest() has already been called")}function rt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function st(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function nt(t){return"string"==typeof t&&(t=function(t){if("string"!=typeof t)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(t))}(t)),et(t),t}class at{}function ot(t){const e=e=>t().update(nt(e)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}const ct=BigInt(2**32-1),ht=BigInt(32);function ut(t,e=!1){return e?{h:Number(t&ct),l:Number(t>>ht&ct)}:{h:0|Number(t>>ht&ct),l:0|Number(t&ct)}}const dt=(t,e,i)=>t>>>i,lt=(t,e,i)=>t<<32-i|e>>>i,ft=(t,e,i)=>t>>>i|e<<32-i,pt=(t,e,i)=>t<<32-i|e>>>i,gt=(t,e,i)=>t<<64-i|e>>>i-32,yt=(t,e,i)=>t>>>i-32|e<<64-i;function bt(t,e,i,r){const s=(e>>>0)+(r>>>0);return{h:t+i+(s/2**32|0)|0,l:0|s}}const mt=(t,e,i)=>(t>>>0)+(e>>>0)+(i>>>0),wt=(t,e,i,r)=>e+i+r+(t/2**32|0)|0,vt=(t,e,i,r)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),It=(t,e,i,r,s)=>e+i+r+s+(t/2**32|0)|0,kt=(t,e,i,r,s)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0)+(s>>>0),St=(t,e,i,r,s,n)=>e+i+r+s+n+(t/2**32|0)|0;class Et extends at{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,i,r){super(),this.blockLen=t,this.outputLen=e,this.padOffset=i,this.isLE=r,this.buffer=new Uint8Array(t),this.view=st(this.buffer)}update(t){it(this),et(t=nt(t));const{view:e,buffer:i,blockLen:r}=this,s=t.length;for(let n=0;n<s;){const a=Math.min(r-this.pos,s-n);if(a===r){const e=st(t);for(;r<=s-n;n+=r)this.process(e,n);continue}i.set(t.subarray(n,n+a),this.pos),this.pos+=a,n+=a,this.pos===r&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){it(this),function(t,e){et(t);const i=e.outputLen;if(t.length<i)throw new Error(`digestInto() expects output buffer of length at least ${i}`)}(t,this),this.finished=!0;const{buffer:e,view:i,blockLen:r,isLE:s}=this;let{pos:n}=this;e[n++]=128,rt(this.buffer.subarray(n)),this.padOffset>r-n&&(this.process(i,0),n=0);for(let t=n;t<r;t++)e[t]=0;!function(t,e,i,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,i,r);const s=BigInt(32),n=BigInt(4294967295),a=Number(i>>s&n),o=Number(i&n),c=r?4:0,h=r?0:4;t.setUint32(e+c,a,r),t.setUint32(e+h,o,r)}(i,r-8,BigInt(8*this.length),s),this.process(i,0);const a=st(t),o=this.outputLen;if(o%4!=0)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t<c;t++)a.setUint32(4*t,h[t],s)}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const i=t.slice(0,e);return this.destroy(),i}_cloneInto(t){t||=new this.constructor,t.set(...this.get());const{blockLen:e,buffer:i,length:r,finished:s,destroyed:n,pos:a}=this;return t.destroyed=n,t.finished=s,t.length=r,t.pos=a,r%e!==0&&t.buffer.set(i),t}clone(){return this._cloneInto()}}const xt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Pt=Uint32Array.from([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]),_t=new Uint32Array(64);class At extends Et{A=0|xt[0];B=0|xt[1];C=0|xt[2];D=0|xt[3];E=0|xt[4];F=0|xt[5];G=0|xt[6];H=0|xt[7];constructor(t=32){super(64,t,8,!1)}get(){const{A:t,B:e,C:i,D:r,E:s,F:n,G:a,H:o}=this;return[t,e,i,r,s,n,a,o]}set(t,e,i,r,s,n,a,o){this.A=0|t,this.B=0|e,this.C=0|i,this.D=0|r,this.E=0|s,this.F=0|n,this.G=0|a,this.H=0|o}process(t,e){for(let i=0;i<16;i++,e+=4)_t[i]=t.getUint32(e);for(let t=16;t<64;t++){const e=_t[t-15],i=_t[t-2],r=L(e),s=M(i);_t[t]=P(P(r,_t[t-7]),P(s,_t[t-16]))}let{A:i,B:r,C:s,D:n,E:a,F:o,G:c,H:h}=this;for(let t=0;t<64;t++){const e=N(h,B(a),T(a,o,c),Pt[t],_t[t]),u=P(R(i),C(i,r,s));h=c,c=o,o=a,a=P(n,e),n=s,s=r,r=i,i=P(e,u)}this.A=P(this.A,i),this.B=P(this.B,r),this.C=P(this.C,s),this.D=P(this.D,n),this.E=P(this.E,a),this.F=P(this.F,o),this.G=P(this.G,c),this.H=P(this.H,h)}roundClean(){rt(_t)}destroy(){rt(this.buffer),this.set(0,0,0,0,0,0,0,0)}}const Nt=ot(()=>new At),Ot=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Tt=function(t,e=!1){const i=t.length,r=new Uint32Array(i),s=new Uint32Array(i);for(let n=0;n<i;n++){const{h:i,l:a}=ut(t[n],e);r[n]=i,s[n]=a}return[r,s]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Ct=Tt[0],Rt=Tt[1],Bt=new Uint32Array(80),Lt=new Uint32Array(80);class Mt extends Et{Ah=0|Ot[0];Al=0|Ot[1];Bh=0|Ot[2];Bl=0|Ot[3];Ch=0|Ot[4];Cl=0|Ot[5];Dh=0|Ot[6];Dl=0|Ot[7];Eh=0|Ot[8];El=0|Ot[9];Fh=0|Ot[10];Fl=0|Ot[11];Gh=0|Ot[12];Gl=0|Ot[13];Hh=0|Ot[14];Hl=0|Ot[15];constructor(t=64){super(128,t,16,!1)}get(){const{Ah:t,Al:e,Bh:i,Bl:r,Ch:s,Cl:n,Dh:a,Dl:o,Eh:c,El:h,Fh:u,Fl:d,Gh:l,Gl:f,Hh:p,Hl:g}=this;return[t,e,i,r,s,n,a,o,c,h,u,d,l,f,p,g]}set(t,e,i,r,s,n,a,o,c,h,u,d,l,f,p,g){this.Ah=0|t,this.Al=0|e,this.Bh=0|i,this.Bl=0|r,this.Ch=0|s,this.Cl=0|n,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|h,this.Fh=0|u,this.Fl=0|d,this.Gh=0|l,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(t,e){for(let i=0;i<16;i++,e+=4)Bt[i]=t.getUint32(e),Lt[i]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|Bt[t-15],i=0|Lt[t-15],r=ft(e,i,1)^ft(e,i,8)^dt(e,0,7),s=pt(e,i,1)^pt(e,i,8)^lt(e,i,7),n=0|Bt[t-2],a=0|Lt[t-2],o=ft(n,a,19)^gt(n,a,61)^dt(n,0,6),c=pt(n,a,19)^yt(n,a,61)^lt(n,a,6),h=vt(s,c,Lt[t-7],Lt[t-16]),u=It(h,r,o,Bt[t-7],Bt[t-16]);Bt[t]=0|u,Lt[t]=0|h}let{Ah:i,Al:r,Bh:s,Bl:n,Ch:a,Cl:o,Dh:c,Dl:h,Eh:u,El:d,Fh:l,Fl:f,Gh:p,Gl:g,Hh:y,Hl:b}=this;for(let t=0;t<80;t++){const e=ft(u,d,14)^ft(u,d,18)^gt(u,d,41),m=pt(u,d,14)^pt(u,d,18)^yt(u,d,41),w=u&l^~u&p,v=kt(b,m,d&f^~d&g,Rt[t],Lt[t]),I=St(v,y,e,w,Ct[t],Bt[t]),k=0|v,S=ft(i,r,28)^gt(i,r,34)^gt(i,r,39),E=pt(i,r,28)^yt(i,r,34)^yt(i,r,39),x=i&s^i&a^s&a,P=r&n^r&o^n&o;y=0|p,b=0|g,p=0|l,g=0|f,l=0|u,f=0|d,({h:u,l:d}=bt(0|c,0|h,0|I,0|k)),c=0|a,h=0|o,a=0|s,o=0|n,s=0|i,n=0|r;const _=mt(E,P,k);i=wt(_,S,x,I),r=0|_}({h:i,l:r}=bt(i,r,this.Ah,this.Al)),({h:s,l:n}=bt(s,n,this.Bh,this.Bl)),({h:a,l:o}=bt(a,o,this.Ch,this.Cl)),({h:c,l:h}=bt(c,h,this.Dh,this.Dl)),({h:u,l:d}=bt(u,d,this.Eh,this.El)),({h:l,l:f}=bt(l,f,this.Fh,this.Fl)),({h:p,l:g}=bt(p,g,this.Gh,this.Gl)),({h:y,l:b}=bt(y,b,this.Hh,this.Hl)),this.set(i,r,s,n,a,o,c,h,u,d,l,f,p,g,y,b)}roundClean(){rt(Bt,Lt)}destroy(){rt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Ft=ot(()=>new Mt);class Ut extends at{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){super(),function(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash should be wrapped by utils.createHasher");tt(t.outputLen),tt(t.blockLen)}(t);const i=nt(e);if(this.iHash=t.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,s=new Uint8Array(r);s.set(i.length>r?t.create().update(i).digest():i);for(let t=0;t<s.length;t++)s[t]^=54;this.iHash.update(s),this.oHash=t.create();for(let t=0;t<s.length;t++)s[t]^=106;this.oHash.update(s),rt(s)}update(t){return it(this),this.iHash.update(t),this}digestInto(t){it(this),et(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});const{oHash:e,iHash:i,finished:r,destroyed:s,blockLen:n,outputLen:a}=this;return t.finished=r,t.destroyed=s,t.blockLen=n,t.outputLen=a,t.oHash=e._cloneInto(t.oHash??void 0),t.iHash=i._cloneInto(t.iHash??void 0),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}(()=>{const t=new ArrayBuffer(4),e=new Uint32Array(t),i=new Uint8Array(t);e[0]=16909060,i[0]})();class Dt{buffer;pos;capacity;constructor(t,e=256){if(null!=t&&t.length>0){const i=t.reduce((t,e)=>t+e.length,0);e=Math.max(e,i)}if(this.buffer=new Uint8Array(e),this.pos=0,this.capacity=e,null!=t)for(const e of t)this.write(e)}getLength(){return this.pos}toUint8Array(){return this.buffer.slice(0,this.pos)}toArray(){return Array.from(this.toUint8Array())}toUint8ArrayZeroCopy(){return this.buffer.subarray(0,this.pos)}ensureCapacity(t){if(this.pos+t>this.capacity){let e=2*this.capacity;for(;this.pos+t>e;)e*=2;const i=new Uint8Array(e);i.set(this.buffer),this.buffer=i,this.capacity=e}}write(t){const e=t instanceof Uint8Array?t:new Uint8Array(t);return this.ensureCapacity(e.length),this.buffer.set(e,this.pos),this.pos+=e.length,this}writeReverse(t){const e=t instanceof Uint8Array?t:new Uint8Array(t);this.ensureCapacity(e.length);for(let t=e.length-1;t>=0;t--)this.buffer[this.pos]=e[t],this.pos+=1;return this}writeUInt8(t){return this.ensureCapacity(1),this.buffer[this.pos]=255&t,this.pos+=1,this}writeInt8(t){return this.writeUInt8(t),this}writeUInt16LE(t){return this.ensureCapacity(2),this.buffer[this.pos]=255&t,this.buffer[this.pos+1]=t>>8&255,this.pos+=2,this}writeUInt16BE(t){return this.ensureCapacity(2),this.buffer[this.pos]=t>>8&255,this.buffer[this.pos+1]=255&t,this.pos+=2,this}writeInt16LE(t){return this.writeUInt16LE(65535&t),this}writeInt16BE(t){return this.writeUInt16BE(65535&t),this}writeUInt32LE(t){return this.ensureCapacity(4),this.buffer[this.pos]=255&t,this.buffer[this.pos+1]=t>>8&255,this.buffer[this.pos+2]=t>>16&255,this.buffer[this.pos+3]=t>>24&255,this.pos+=4,this}writeUInt32BE(t){return this.ensureCapacity(4),this.buffer[this.pos]=t>>24&255,this.buffer[this.pos+1]=t>>16&255,this.buffer[this.pos+2]=t>>8&255,this.buffer[this.pos+3]=255&t,this.pos+=4,this}writeInt32LE(t){return this.writeUInt32LE(t>>>0),this}writeInt32BE(t){return this.writeUInt32BE(t>>>0),this}writeUInt64BEBn(t){const e=t.toArray("be",8);return this.write(e),this}writeUInt64LEBn(t){const e=t.toArray("be",8);return this.writeReverse(e),this}writeUInt64LE(t){const e=new a(t).toArray("be",8);return this.writeReverse(e),this}writeVarIntNum(t){const e=se.varIntNum(t);return this.write(e),this}writeVarIntBn(t){const e=se.varIntBn(t);return this.write(e),this}reset(){this.pos=0}}class Ht{bin;pos;length;static makeReader(t,e=0){if(t instanceof Uint8Array)return new Ht(t,e);if(Array.isArray(t))return new ne(t,e);throw new Error("ReaderUint8Array.makeReader: bin must be Uint8Array or number[]")}constructor(t=new Uint8Array(0),e=0){if(t instanceof Uint8Array)this.bin=t;else{if(!Array.isArray(t))throw new Error("ReaderUint8Array constructor: bin must be Uint8Array or number[]");this.bin=new Uint8Array(t)}this.pos=e,this.length=this.bin.length}eof(){return this.pos>=this.length}read(t=this.length){const e=this.pos,i=this.pos+t;return this.pos=i,this.bin.slice(e,i)}readReverse(t=this.length){const e=new Uint8Array(t);for(let i=0;i<t;i++)e[i]=this.bin[this.pos+t-1-i];return this.pos+=t,e}readUInt8(){const t=this.bin[this.pos];return this.pos+=1,t}readInt8(){const t=this.bin[this.pos];return this.pos+=1,128&t?t-256:t}readUInt16BE(){const t=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,t}readInt16BE(){const t=this.readUInt16BE();return 32768&t?t-65536:t}readUInt16LE(){const t=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,t}readInt16LE(){const t=this.readUInt16LE();return 32768&t?t-65536:t}readUInt32BE(){const t=16777216*this.bin[this.pos]+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,t}readInt32BE(){const t=this.readUInt32BE();return 2147483648&t?t-4294967296:t}readUInt32LE(){const t=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,t}readInt32LE(){const t=this.readUInt32LE();return 2147483648&t?t-4294967296:t}readUInt64BEBn(){const t=Array.from(this.bin.slice(this.pos,this.pos+8)),e=new a(t);return this.pos=this.pos+8,e}readUInt64LEBn(){const t=Array.from(this.readReverse(8));return new a(t)}readInt64LEBn(){const t=new a(2).pow(new a(63)),e=new a(2).pow(new a(64)),i=Array.from(this.readReverse(8));let r=new a(i);return r.gte(t)&&(r=r.sub(e)),r}readVarIntNum(t=!0){const e=this.readUInt8();let i;switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(i=t?this.readInt64LEBn():this.readUInt64LEBn(),i.lte(new a(2).pow(new a(53))))return i.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return e}}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){const t=this.readUInt8();switch(t){case 253:return new a(this.readUInt16LE());case 254:return new a(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new a(t)}}}const qt="undefined"!=typeof globalThis?globalThis.Buffer:void 0,Vt=null!=qt&&"function"==typeof qt.from,Kt="0123456789abcdef",$t=new Array(256);for(let t=0;t<256;t++)$t[t]=Kt[t>>4&15]+Kt[15&t];const jt=t=>{if(Vt)return qt.from(t).toString("hex");if(0===t.length)return"";const e=new Array(t.length);for(let i=0;i<t.length;i++)e[i]=$t[255&t[i]];return e.join("")},zt=(t,e)=>t instanceof Uint8Array?t:new Uint8Array(Wt(t,e)),Wt=(t,e)=>{if(Array.isArray(t))return t.slice();if(void 0===t)return[];if("string"!=typeof t)return Array.from(t,t=>0|t);switch(e){case"hex":return Xt(t);case"base64":return function(t){if("string"!=typeof t)throw new TypeError("msg must be a string");let e=t.trim().replace(/[\r\n\t\f\v ]+/g,"");e=e.replace(/-/g,"+").replace(/_/g,"/");const i=e.indexOf("=");if(-1!==i){const t=e.slice(i);if(!/^={1,2}$/.test(t))throw new Error("Invalid base64 padding");if(e.slice(0,i).includes("="))throw new Error("Invalid base64 padding");e=e.slice(0,i)}const r=[];let s=0,n=0;for(let t=0;t<e.length;t++){const i=e.charCodeAt(t);let a=-1;if(i>=65&&i<=90)a=i-65;else if(i>=97&&i<=122)a=i-97+26;else if(i>=48&&i<=57)a=i-48+52;else if(43===i)a=62;else{if(47!==i)throw new Error(`Invalid base64 character at index ${t}`);a=63}for(s=s<<6|a,n+=6;n>=8;)n-=8,r.push(s>>n&255),s&=(1<<n)-1}return r}(t);default:return i=t,Array.from((new TextEncoder).encode(i))}var i},Gt=new Int8Array(256).fill(-1);for(let t=0;t<10;t++)Gt[48+t]=t;for(let t=0;t<6;t++)Gt[65+t]=10+t,Gt[97+t]=10+t;const Xt=t=>{p(t);const e=t.length%2==0?t:"0"+t;if(Vt)return Array.from(qt.from(e,"hex"));const i=new Array(e.length/2);let r=0;for(let t=0;t<e.length;t+=2){const s=Gt[e.charCodeAt(t)],n=Gt[e.charCodeAt(t+1)];i[r++]=s<<4|n}return i},Yt=t=>(new TextDecoder).decode(new Uint8Array(t)),Jt=(t,e)=>{switch(e){case"hex":return jt(t);case"utf8":return Yt(t);default:return t}};function Zt(t){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let i,r="";for(i=0;i<t.length;i+=3){const s=t[i],n=i+1<t.length?t[i+1]:0,a=i+2<t.length?t[i+2]:0,o=(3&s)<<4|n>>4,c=(15&n)<<2|a>>6,h=63&a;r+=e.charAt(s>>2)+e.charAt(o),r+=i+1<t.length?e.charAt(c):"=",r+=i+2<t.length?e.charAt(h):"="}return r}const Qt="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",te=t=>{if(""===t||"string"!=typeof t)throw new Error(`Expected base58 string but got “${t}”`);const e=t.match(/[IOl0]/gmu);if(null!==e)throw new Error(`Invalid base58 character “${e.join("")}”`);const i=t.match(/^1+/gmu),r=null!==i?i[0].length:0,s=(t.length-r)*(Math.log(58)/Math.log(256))+1>>>0,n=new Uint8Array([...new Uint8Array(r),...(t.match(/./gmu)??[]).map(t=>Qt.indexOf(t)).reduce((t,e)=>t.map(t=>{const i=58*t+e;return e=i>>8,i}),new Uint8Array(s)).reverse().filter((a=!1,t=>a=a||t))]);var a;return[...n]},ee=t=>{const e=Array(256).fill(-1);for(let t=0;t<58;++t)e[Qt.charCodeAt(t)]=t;const i=[];for(const r of t){let t=r;for(let r=0;r<i.length;++r){const s=(e[i[r]]<<8)+t;i[r]=Qt.charCodeAt(s%58),t=s/58|0}for(;0!==t;)i.push(Qt.charCodeAt(t%58)),t=t/58|0}for(const e of t){if(0!==e)break;i.push("1".charCodeAt(0))}return i.reverse(),String.fromCharCode(...i)},ie=(t,e=[0])=>{let i=Y([...e,...t]);return i=[...e,...t,...i.slice(0,4)],ee(i)},re=(t,e,i=1)=>{const r=te(t);let s=r.slice(0,i),n=r.slice(i,-4),a=[...s,...n];return a=Y(a),r.slice(-4).forEach((t,e)=>{if(t!==a[e])throw new Error("Invalid checksum")}),"hex"===e&&(s=jt(s),n=jt(n)),{prefix:s,data:n}};class se{bufs;length;constructor(t){this.bufs=void 0!==t?t:[],this.length=0;for(const t of this.bufs)this.length+=t.length}getLength(){return this.length}toUint8Array(){const t=new Uint8Array(this.length);let e=0;for(const i of this.bufs)t.set(i,e),e+=i.length;return t}toArray(){const t=this.length,e=new Array(t);let i=0;for(const t of this.bufs)if(t instanceof Uint8Array)for(let r=0;r<t.length;r++)e[i++]=t[r];else{const r=t;for(let t=0;t<r.length;t++)e[i++]=r[t]}return e}toHex(){return this.toArray().map(t=>t.toString(16).padStart(2,"0")).join("")}write(t){return this.bufs.push(t),this.length+=t.length,this}writeReverse(t){const e=new Array(t.length);for(let i=0;i<e.length;i++)e[i]=t[t.length-1-i];return this.write(e)}writeUInt8(t){const e=new Array(1);return e[0]=255&t,this.write(e),this}writeInt8(t){const e=new Array(1);return e[0]=255&t,this.write(e),this}writeUInt16BE(t){const e=[t>>8&255,255&t];return this.write(e)}writeInt16BE(t){return this.writeUInt16BE(65535&t)}writeUInt16LE(t){const e=[255&t,t>>8&255];return this.write(e)}writeInt16LE(t){return this.writeUInt16LE(65535&t)}writeUInt32BE(t){const e=[t>>24&255,t>>16&255,t>>8&255,255&t];return this.write(e)}writeInt32BE(t){return this.writeUInt32BE(t>>>0)}writeUInt32LE(t){const e=[255&t,t>>8&255,t>>16&255,t>>24&255];return this.write(e)}writeInt32LE(t){return this.writeUInt32LE(t>>>0)}writeUInt64BEBn(t){const e=t.toArray("be",8);return this.write(e),this}writeUInt64LEBn(t){const e=t.toArray("be",8);return this.writeReverse(e),this}writeUInt64LE(t){if(-1===t)this.write(new Array(8).fill(255));else{const e=new a(t).toArray("be",8);this.writeReverse(e)}return this}writeVarIntNum(t){const e=se.varIntNum(t);return this.write(e),this}writeVarIntBn(t){const e=se.varIntBn(t);return this.write(e),this}static varIntNum(t){let e;if(t<0)return this.varIntBn(new a(t));if(t<253)e=[t];else if(t<65536)e=[253,255&t,t>>8&255];else if(t<4294967296)e=[254,255&t,t>>8&255,t>>16&255,t>>24&255];else{const i=4294967295&t,r=4294967295&Math.floor(t/4294967296);e=[255,255&i,i>>8&255,i>>16&255,i>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255]}return e}static varIntBn(t){let e;if(t.isNeg()&&(t=t.add(ce)),t.ltn(253))e=[t.toNumber()];else if(t.ltn(65536)){const i=t.toNumber();e=[253,255&i,i>>8&255]}else if(t.lt(new a(4294967296))){const i=t.toNumber();e=[254,255&i,i>>8&255,i>>16&255,i>>24&255]}else{const i=new se;i.writeUInt8(255),i.writeUInt64LEBn(t),e=i.toArray()}return e}}class ne{bin;pos;length;constructor(t=[],e=0){this.bin=t,this.pos=e,this.length=t.length}eof(){return this.pos>=this.length}read(t=this.length){const e=this.pos,i=this.pos+t;return this.pos=i,this.bin.slice(e,i)}readReverse(t=this.length){const e=new Array(t);for(let i=0;i<t;i++)e[i]=this.bin[this.pos+t-1-i];return this.pos+=t,e}readUInt8(){const t=this.bin[this.pos];return this.pos+=1,t}readInt8(){const t=this.bin[this.pos];return this.pos+=1,128&t?t-256:t}readUInt16BE(){const t=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,t}readInt16BE(){const t=this.readUInt16BE();return 32768&t?t-65536:t}readUInt16LE(){const t=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,t}readInt16LE(){const t=this.readUInt16LE();return 32768&t?t-65536:t}readUInt32BE(){const t=16777216*this.bin[this.pos]+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,t}readInt32BE(){const t=this.readUInt32BE();return 2147483648&t?t-4294967296:t}readUInt32LE(){const t=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,t}readInt32LE(){const t=this.readUInt32LE();return 2147483648&t?t-4294967296:t}readUInt64BEBn(){const t=this.bin.slice(this.pos,this.pos+8),e=new a(t);return this.pos=this.pos+8,e}readUInt64LEBn(){const t=this.readReverse(8);return new a(t)}readInt64LEBn(){const t=this.readReverse(8);let e=new a(t);return e.gte(oe)&&(e=e.sub(ce)),e}readVarIntNum(t=!0){const e=this.readUInt8();let i;switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(i=t?this.readInt64LEBn():this.readUInt64LEBn(),i.lte(new a(2).pow(new a(53))))return i.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return e}}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){const t=this.readUInt8();switch(t){case 253:return new a(this.readUInt16LE());case 254:return new a(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new a(t)}}}const ae=t=>{if(0===t.length)return t;const e=t[t.length-1];if(127&e)return t;if(1===t.length)return[];if(128&t[t.length-2])return t;for(let i=t.length-1;i>0;i--)if(0!==t[i-1])return 128&t[i-1]?(t[i]=e,t.slice(0,i+1)):(t[i-1]|=e,t.slice(0,i));return[]},oe=new a(2).pow(new a(63)),ce=new a(2).pow(new a(64));function he(t,e="Expected a valid value, but got undefined or null."){if(null==t)throw new Error(e);return t}function ue(t,e,i){const r=-t,s=(e.X^i.X)&r,n=(e.Y^i.Y)&r,a=(e.Z^i.Z)&r;e.X^=s,i.X^=s,e.Y^=n,i.Y^=n,e.Z^=a,i.Z^=a}const de=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,le=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,fe=(1n<<256n)-1n;function pe(t){let e=t>>256n;return e=(t=(t&fe)+(e<<32n)+977n*e)>>256n,(t=(t&fe)+(e<<32n)+977n*e)>=de&&(t-=de),t}const ge=t=>pe((t%de+de)%de),ye=(t,e)=>t>=e?t-e:de-(e-t),be=(t,e)=>pe(t*e),me=(t,e)=>pe(t+e),we=t=>{let e=1n,i=0n,r=ge(t),s=de;for(;r>1n;){const t=s/r;[e,i]=[i-e*t,e],[r,s]=[s-r*t,r]}return ge(e)},ve=de+1n>>2n,Ie=BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),ke=BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),Se=new Map,Ee=t=>{const{X:e,Y:i,Z:r}=t;if(0n===i)return{X:0n,Y:1n,Z:0n};const s=be(i,i),n=be(4n,be(e,s)),a=be(3n,be(e,e)),o=ye(be(a,a),be(2n,n));return{X:o,Y:ye(be(a,ye(n,o)),be(8n,be(s,s))),Z:be(2n,be(i,r))}},xe=(t,e)=>{if(0n===t.Z)return e;if(0n===e.Z)return t;const i=be(t.Z,t.Z),r=be(e.Z,e.Z),s=be(t.X,r),n=be(e.X,i),a=be(t.Y,be(r,e.Z)),o=be(e.Y,be(i,t.Z)),c=ye(n,s),h=ye(o,a);if(0n===c)return 0n===h?Ee(t):{X:0n,Y:1n,Z:0n};const u=be(c,c),d=be(c,u),l=be(s,u),f=ye(ye(be(h,h),d),be(2n,l));return{X:f,Y:ye(be(h,ye(l,f)),be(a,d)),Z:be(c,be(t.Z,e.Z))}},Pe=t=>0n===t.Z?t:{X:t.X,Y:de-t.Y,Z:t.Z},_e=(t,e,i=5)=>{const r=`${i}:${e.x.toString(16)}:${e.y.toString(16)}`;let s,n=Se.get(r);if(void 0===n){const t=1<<i-1;n=new Array(t),s={X:e.x,Y:e.y,Z:1n},n[0]=s;const a=Ee(s);for(let e=1;e<t;e++)n[e]=xe(n[e-1],a);Se.set(r,n)}else s=n[0];const a=[],o=1n<<BigInt(i),c=o>>1n;let h=t;for(;h>0n;)if(0n==(1n&h))a.push(0),h>>=1n;else{let t=h&o-1n;t>c&&(t-=o),a.push(Number(t)),h-=t,h>>=1n}let u={X:0n,Y:1n,Z:0n};for(let t=a.length-1;t>=0;t--){u=Ee(u);const e=a[t];if(0!==e){const t=Math.abs(e)>>1,i=e>0?n[t]:Pe(n[t]);u=xe(u,i)}}return u},Ae=t=>{let e=t%le;return e<0n&&(e+=le),e},Ne=(t,e)=>Ae(t*e),Oe=t=>{let e=1n,i=0n,r=Ae(t),s=le;for(;r>1n;){const t=s/r;[e,i]=[i-e*t,e],[r,s]=[s-r*t,r]}return Ae(e)};class Te extends d{x;y;inf;static _assertOnCurve(t){if(!t.validate())throw new Error("Invalid point");return t}static fromDER(t){if((4===t[0]||6===t[0]||7===t[0])&&t.length-1==64){if(6===t[0]){if(t[t.length-1]%2!=0)throw new Error("Point string value is wrong length")}else if(7===t[0]&&t[t.length-1]%2!=1)throw new Error("Point string value is wrong length");const e=new Te(t.slice(1,33),t.slice(33,65));return Te._assertOnCurve(e)}if((2===t[0]||3===t[0])&&t.length-1==32)return Te._assertOnCurve(Te.fromX(t.slice(1,33),3===t[0]));throw new Error("Unknown point format")}static fromString(t){const e=Wt(t,"hex");return Te._assertOnCurve(Te.fromDER(e))}static fromX(t,e){let i=(t=>a.isBN(t)?BigInt("0x"+t.toString(16)):"string"==typeof t?BigInt("0x"+t):Array.isArray(t)?BigInt("0x"+jt(t)):BigInt(t))(t);i=ge(i);var r;const s=(t=>{const e=((t,e)=>{let i=1n;for(t=ge(t);e>0n;)0n!=(1n&e)&&(i=be(i,t)),t=be(t,t),e>>=1n;return i})(t,ve);return be(e,e)!==ge(t)?null:e})(me(be(be(r=i,r),i),7n));if(null===s)throw new Error("Invalid point");let n=s;(1n&n)!=(e?1n:0n)&&(n=ye(de,n));const o=new a(i.toString(16),16),c=new a(n.toString(16),16);return Te._assertOnCurve(new Te(o,c))}static fromJSON(t,e){"string"==typeof t&&(t=JSON.parse(t));let i=new Te(t[0],t[1],e);if(i=Te._assertOnCurve(i),"object"!=typeof t[2]||null===t[2])return i;const r=t[2],s=t=>{const i=new Te(t[0],t[1],e);return Te._assertOnCurve(i)};return i.precomputed={beta:null,doubles:"object"==typeof r.doubles&&null!==r.doubles?{step:r.doubles.step,points:[i].concat(r.doubles.points.map(s))}:void 0,naf:"object"==typeof r.naf&&null!==r.naf?{wnd:r.naf.wnd,points:[i].concat(r.naf.points.map(s))}:void 0},i}constructor(t,e,i=!0){super("affine"),this.precomputed=null,null===t&&null===e?(this.x=null,this.y=null,this.inf=!0):(a.isBN(t)||(t=new a(t,16)),this.x=t,a.isBN(e)||(e=new a(e,16)),this.y=e,i&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),null===this.x.red&&(this.x=this.x.toRed(this.curve.red)),null===this.y.red&&(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}validate(){if(this.inf||null==this.x||null==this.y)return!1;try{const t=BigInt("0x"+this.x.fromRed().toString(16)),e=BigInt("0x"+this.y.fromRed().toString(16));return be(e,e)===me(be(be(t,t),t),7n)}catch{return!1}}encode(t=!0,e){if(this.inf)return"hex"===e?"00":[0];const i=this.curve.p.byteLength(),r=this.getX().toArray("be",i);let s;return s=t?[this.getY().isEven()?2:3].concat(r):[4].concat(r,this.getY().toArray("be",i)),"hex"!==e?s:jt(s)}toString(){return this.encode(!0,"hex")}toJSON(){return null==this.precomputed?[this.x,this.y]:[this.x,this.y,"object"==typeof this.precomputed&&null!==this.precomputed?{doubles:null!=this.precomputed.doubles?{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)}:void 0,naf:null!=this.precomputed.naf?{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}:void 0}:void 0]}inspect(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+(this.x?.fromRed()?.toString(16,2)??"undefined")+" y: "+(this.y?.fromRed()?.toString(16,2)??"undefined")+">"}isInfinity(){return this.inf}add(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return new Te(null,null);if(0===this.x?.cmp(t.x??new a(0)))return new Te(null,null);const e={X:BigInt("0x"+this.x.fromRed().toString(16)),Y:BigInt("0x"+this.y.fromRed().toString(16)),Z:1n},i={X:BigInt("0x"+t.x.fromRed().toString(16)),Y:BigInt("0x"+t.y.fromRed().toString(16)),Z:1n},r=xe(e,i);if(0n===r.Z)return new Te(null,null);const s=we(r.Z),n=be(s,s),o=be(r.X,n),c=be(r.Y,be(n,s));return new Te(o.toString(16),c.toString(16))}dbl(){if(this.inf)return this;if(null===this.x||null===this.y)throw new Error("Point coordinates cannot be null");const t=BigInt("0x"+this.x.fromRed().toString(16)),e=BigInt("0x"+this.y.fromRed().toString(16));if(0n===e)return new Te(null,null);const i=Ee({X:t,Y:e,Z:1n}),r=we(i.Z),s=be(r,r),n=be(i.X,s),a=be(i.Y,be(s,r));return new Te(n.toString(16),a.toString(16))}getX(){return(this.x??new a(0)).fromRed()}getY(){return(this.y??new a(0)).fromRed()}mul(t){if(a.isBN(t)||(t=new a(t,16)),this.inf)return this;const e=t.isNeg(),i=e?t.neg():t;let r,s,n=BigInt("0x"+i.toString(16));if(n=ge(n),0n===n)return new Te(null,null);if(0n===n)return new Te(null,null);if(null===this.x||null===this.y)throw new Error("Point coordinates cannot be null");this===this.curve.g?(r=Ie,s=ke):(r=BigInt("0x"+this.x.fromRed().toString(16)),s=BigInt("0x"+this.y.fromRed().toString(16)));const o=_e(n,{x:r,y:s});if(0n===o.Z)return new Te(null,null);const c=we(o.Z),h=be(c,c),u=be(o.X,h),d=be(o.Y,be(h,c)),l=new a(u.toString(16),16),f=new a(d.toString(16),16),p=new Te(l,f);return e?p.neg():p}mulCT(t){if(a.isBN(t)||(t=new a(t,16)),this.inf)return new Te(null,null);const e=t.isNeg(),i=e?t.neg():t;let r=BigInt("0x"+i.toString(16));if(r=ge(r),0n===r)return new Te(null,null);let s={X:0n,Y:1n,Z:0n},n={X:this===this.curve.g?Ie:BigInt("0x"+this.getX().toString(16)),Y:this===this.curve.g?ke:BigInt("0x"+this.getY().toString(16)),Z:1n};const o=r.toString(2);for(let t=0;t<o.length;t++){const e="1"===o[t]?1n:0n;ue(e,s,n),n=xe(s,n),s=Ee(s),ue(e,s,n)}if(0n===s.Z)return new Te(null,null);const c=we(s.Z),h=be(c,c),u=be(s.X,h),d=be(s.Y,be(h,c)),l=new Te(u.toString(16),d.toString(16));return e?l.neg():l}mulAdd(t,e,i){const r=[this,e],s=[t,i];return this._endoWnafMulAdd(r,s)}jmulAdd(t,e,i){const r=[this,e],s=[t,i];return this._endoWnafMulAdd(r,s,!0)}eq(t){return this===t||this.inf===t.inf&&(this.inf||0===(this.x??new a(0)).cmp(t.x??new a(0))&&0===(this.y??new a(0)).cmp(t.y??new a(0)))}neg(t){if(this.inf)return this;const e=new Te(this.x,(this.y??new a(0)).redNeg());if(!0===t&&null!=this.precomputed){const t=this.precomputed,i=t=>t.neg();e.precomputed={naf:null!=t.naf?{wnd:t.naf.wnd,points:t.naf.points.map(i)}:void 0,doubles:null!=t.doubles?{step:t.doubles.step,points:t.doubles.points.map(t=>t.neg())}:void 0,beta:void 0}}return e}dblp(t){let e=this;for(let i=0;i<t;i++)e=e.dbl();return e}toJ(){return this.inf?new l(null,null,null):new l(this.x,this.y,this.curve.one)}_getBeta(){if("object"!=typeof this.curve.endo)return;const t=this.precomputed;if("object"==typeof t&&null!==t&&"object"==typeof t.beta&&null!==t.beta)return t.beta;const e=new Te((this.x??new a(0)).redMul(this.curve.endo.beta),this.y);if(null!=t){const i=this.curve,r=t=>{if(null===t.x)throw new Error("p.x is null");if(void 0===i.endo||null===i.endo)throw new Error("curve.endo is undefined");return new Te(t.x.redMul(i.endo.beta),t.y)};t.beta=e,e.precomputed={beta:null,naf:null!=t.naf?{wnd:t.naf.wnd,points:t.naf.points.map(r)}:void 0,doubles:null!=t.doubles?{step:t.doubles.step,points:t.doubles.points.map(r)}:void 0}}return e}_fixedNafMul(t){if("object"!=typeof this.precomputed||null===this.precomputed)throw new Error("_fixedNafMul requires precomputed values for the point");const e=this._getDoubles(),i=this.curve.getNAF(t,1,this.curve._bitLength);let r=(1<<e.step+1)-(e.step%2==0?2:1);r/=3;const s=[];for(let t=0;t<i.length;t+=e.step){let r=0;for(let s=t+e.step-1;s>=t;s--)r=(r<<1)+i[s];s.push(r)}let n=new l(null,null,null),a=new l(null,null,null);for(let t=r;t>0;t--){for(let i=0;i<s.length;i++){const r=s[i];r===t?a=a.mixedAdd(e.points[i]):r===-t&&(a=a.mixedAdd(e.points[i].neg()))}n=n.add(a)}return n.toP()}_wnafMulAdd(t,e,i,r,s){const n=this.curve._wnafT1.map(t=>t.toNumber()),o=this.curve._wnafT2.map(()=>[]),c=this.curve._wnafT3.map(()=>[]);let h=0;for(let i=0;i<r;i++){const r=e[i]._getNAFPoints(t);n[i]=r.wnd,o[i]=r.points}for(let t=r-1;t>=1;t-=2){const r=t-1,s=t;if(1!==n[r]||1!==n[s]){c[r]=this.curve.getNAF(i[r],n[r],this.curve._bitLength),c[s]=this.curve.getNAF(i[s],n[s],this.curve._bitLength),h=Math.max(c[r].length,h),h=Math.max(c[s].length,h);continue}const u=[e[r],null,null,e[s]];0===(e[r].y??new a(0)).cmp(e[s].y??new a(0))?(u[1]=e[r].add(e[s]),u[2]=e[r].toJ().mixedAdd(e[s].neg())):0===(e[r].y??new a(0)).cmp((e[s].y??new a(0)).redNeg())?(u[1]=e[r].toJ().mixedAdd(e[s]),u[2]=e[r].add(e[s].neg())):(u[1]=e[r].toJ().mixedAdd(e[s]),u[2]=e[r].toJ().mixedAdd(e[s].neg()));const d=[-3,-1,-5,-7,0,7,5,1,3],l=this.curve.getJSF(i[r],i[s]);h=Math.max(l[0].length,h),c[r]=new Array(h),c[s]=new Array(h);for(let t=0;t<h;t++){const e=0|l[0][t],i=0|l[1][t];c[r][t]=d[3*(e+1)+(i+1)],c[s][t]=0,o[r]=u}}let u=new l(null,null,null);const d=this.curve._wnafT4;for(let t=h;t>=0;t--){let e=0;for(;t>=0;){let i=!0;for(let e=0;e<r;e++)d[e]=new a("number"==typeof c[e][t]?c[e][t]:0),d[e].isZero()||(i=!1);if(!i)break;e++,t--}if(t>=0&&e++,u=u.dblp(e),t<0)break;const i=new a(1),s=new a(2);for(let t=0;t<r;t++){const e=d[t];let r;0!==e.cmpn(0)&&(r=e.isNeg()?o[t][e.neg().sub(i).div(s).toNumber()].neg():o[t][e.sub(i).div(s).toNumber()],u="affine"===r.type?u.mixedAdd(r):u.add(r))}}for(let t=0;t<r;t++)o[t]=[];return!0===s?u:u.toP()}_endoWnafMulAdd(t,e,i){const r=new Array(2*t.length),s=new Array(2*t.length);let n;for(n=0;n<t.length;n++){const i=this.curve._endoSplit(e[n]);let a=t[n],o=a._getBeta()??new Te(null,null);0!==i.k1.negative&&(i.k1.ineg(),a=a.neg(!0)),0!==i.k2.negative&&(i.k2.ineg(),o=o.neg(!0)),r[2*n]=a,r[2*n+1]=o,s[2*n]=i.k1,s[2*n+1]=i.k2}const a=this._wnafMulAdd(1,r,s,2*n,i);for(let t=0;t<2*n;t++)r[t]=null,s[t]=null;return a}_hasDoubles(t){if(null==this.precomputed)return!1;const e=this.precomputed.doubles;return"object"==typeof e&&e.points.length>=Math.ceil((t.bitLength()+1)/e.step)}_getDoubles(t,e){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.doubles&&null!==this.precomputed.doubles)return this.precomputed.doubles;const i=[this];let r=this;for(let s=0;s<(e??0);s+=t??1){for(let e=0;e<(t??1);e++)r=r.dbl();i.push(r)}return{step:t??1,points:i}}_getNAFPoints(t){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.naf&&null!==this.precomputed.naf)return this.precomputed.naf;const e=[this],i=(1<<t)-1,r=1===i?null:this.dbl();for(let t=1;t<i;t++)null!==r&&(e[t]=e[t-1].add(r));return{wnd:t,points:e}}}let Ce;class Re{p;red;redN;zero;one;two;g;n;a;b;tinv;zeroA;threeA;endo;_endoWnafT1;_endoWnafT2;_wnafT1;_wnafT2;_wnafT3;_wnafT4;_bitLength;static assert(t,e="Elliptic curve assertion failed"){if(!t)throw new Error(e)}getNAF(t,e,i){const r=new Array(Math.max(t.bitLength(),i)+1);r.fill(0);const s=1<<e+1,n=t.clone();for(let t=0;t<r.length;t++){let e;const i=n.andln(s-1);n.isOdd()?(e=i>(s>>1)-1?(s>>1)-i:i,n.isubn(e)):e=0,r[t]=e,n.iushrn(1)}return r}getJSF(t,e){const i=[[],[]];t=t.clone(),e=e.clone();let r=0,s=0;for(;t.cmpn(-r)>0||e.cmpn(-s)>0;){let n,a,o=t.andln(3)+r&3,c=e.andln(3)+s&3;if(3===o&&(o=-1),3===c&&(c=-1),1&o){const e=t.andln(7)+r&7;n=3!==e&&5!==e||2!==c?o:-o}else n=0;if(i[0].push(n),1&c){const t=e.andln(7)+s&7;a=3!==t&&5!==t||2!==o?c:-c}else a=0;i[1].push(a),2*r===n+1&&(r=1-r),2*s===a+1&&(s=1-s),t.iushrn(1),e.iushrn(1)}return i}static cachedProperty(t,e,i){const r="_"+e;t.prototype[e]=function(){return void 0!==this[r]?this[r]:this[r]=i.call(this)}}static parseBytes(t){return"string"==typeof t?Wt(t,"hex"):t}static intFromLE(t){return new a(t,"hex","le")}constructor(){if(void 0!==Ce)return Ce;Ce=this;const t={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",beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",{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"]]}}]};this.p=new a(t.p,16),this.red=new h(t.prime),this.zero=new a(0).toRed(this.red),this.one=new a(1).toRed(this.red),this.two=new a(2).toRed(this.red),this.n=new a(t.n,16),this.g=Te.fromJSON(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.bitLength(),this.redN=this.n.toRed(this.red),this.a=new a(t.a,16).toRed(this.red),this.b=new a(t.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(t),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}_getEndomorphism(t){if(!this.zeroA||1!==this.p.modrn(3))return;let e,i,r;if(void 0!==t.beta)e=new a(t.beta,16).toRed(this.red);else{const t=this._getEndoRoots(this.p);if(null===t)throw new Error("Failed to get endomorphism roots for beta.");e=t[0].cmp(t[1])<0?t[0]:t[1],e=e.toRed(this.red)}if(void 0!==t.lambda)i=new a(t.lambda,16);else{const t=this._getEndoRoots(this.n);if(null===t)throw new Error("Failed to get endomorphism roots for lambda.");if(null==this.g)throw new Error("Curve generator point (g) is not defined.");const r=this.g.mul(t[0])?.x,s=null!=this.g.x?this.g.x.redMul(e):void 0;if(null!=r&&null!=s&&0===r.cmp(s))i=t[0];else{if(i=t[1],null==this.g)throw new Error("Curve generator point (g) is not defined.");const r=this.g.mul(i)?.x,s=null!=this.g.x?this.g.x.redMul(e):void 0;if(null==r||null==s)throw new Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");Re.assert(0===r.cmp(s),"Lambda selection does not match computed beta.")}}return r="object"==typeof t.basis&&null!==t.basis?t.basis.map(function(t){return{a:new a(t.a,16),b:new a(t.b,16)}}):this._getEndoBasis(i),{beta:e,lambda:i,basis:r}}_getEndoRoots(t){const e=t===this.p?this.red:new u(t),i=new a(2).toRed(e).redInvm(),r=i.redNeg(),s=new a(3).toRed(e).redNeg().redSqrt().redMul(i);return[r.redAdd(s).fromRed(),r.redSub(s).fromRed()]}_getEndoBasis(t){const e=this.n.ushrn(Math.floor(this.n.bitLength()/2));let i,r,s,n,o,c,h=t,u=this.n.clone(),d=new a(1),l=new a(0),f=new a(0),p=new a(1),g=new a(0),y=0,b=new a(0),m=new a(0);for(;0!==h.cmpn(0);){const t=u.div(h);b=u.sub(t.mul(h)),m=f.sub(t.mul(d));const a=p.sub(t.mul(l));if(void 0===s&&b.cmp(e)<0)i=g.neg(),r=d,s=b.neg(),n=m;else if(void 0!==s&&2===++y)break;g=b,u=h,h=b,f=d,d=m,p=l,l=a}if(void 0===i||void 0===r||void 0===s||void 0===n)throw new Error("Failed to compute Endo Basis values");o=b.neg(),c=m;const w=s.sqr().add(n.sqr());return o.sqr().add(c.sqr()).cmp(w)>=0&&(o=i,c=r),0!==s.negative&&(s=s.neg(),n=n.neg()),0!==o.negative&&(o=o.neg(),c=c.neg()),[{a:s,b:n},{a:o,b:c}]}_endoSplit(t){if(null==this.endo)throw new Error("Endomorphism is not defined.");const e=this.endo.basis,i=e[0],r=e[1],s=r.b.mul(t).divRound(this.n),n=i.b.neg().mul(t).divRound(this.n),a=s.mul(i.a),o=n.mul(r.a),c=s.mul(i.b),h=n.mul(r.b);return{k1:t.sub(a).sub(o),k2:c.add(h).neg()}}validate(t){if(t.inf)return!0;const e=t.x,i=t.y;if(null===e||null===i)throw new Error("Point coordinates cannot be null");const r=this.a.redMul(e),s=e.redSqr().redMul(e).redIAdd(r).redIAdd(this.b);return 0===i.redSqr().redISub(s).cmpn(0)}}class Be{r;s;static fromDER(t,e){const i=(t,e)=>{const i=t[e.place++];if(128&i)throw new Error("Invalid DER entity length");return i};t=Wt(t,e);const r=new class{place;constructor(){this.place=0}};if(48!==t[r.place++])throw new Error("Signature DER must start with 0x30");if(i(t,r)+r.place!==t.length)throw new Error("Signature DER invalid");if(2!==t[r.place++])throw new Error("Signature DER invalid");const s=i(t,r);let n=t.slice(r.place,s+r.place);if(r.place+=s,2!==t[r.place++])throw new Error("Signature DER invalid");const o=i(t,r);if(t.length!==o+r.place)throw new Error("Invalid R-length in signature DER");let c=t.slice(r.place,o+r.place);if(0===n[0]){if(!(128&n[1]))throw new Error("Invalid R-value in signature DER");n=n.slice(1)}if(0===c[0]){if(!(128&c[1]))throw new Error("Invalid S-value in signature DER");c=c.slice(1)}return new Be(new a(n),new a(c))}static fromCompact(t,e){if(65!==(t=Wt(t,e)).length)throw new Error("Invalid Compact Signature");const i=t[0];if(i<27||i>=35)throw new Error("Invalid Compact Byte");return new Be(new a(t.slice(1,33)),new a(t.slice(33,65)))}constructor(t,e){this.r=t,this.s=e}verify(t,e,i){const r=new a(X(t,i),16);return Ke(r,this,e)}toString(t){return this.toDER(t)}toDER(t){const e=(t,e)=>{if(!(e<128))throw new Error("len must be < 0x80");t.push(e)},i=t=>{let e=0;const i=t.length-1;for(;0===t[e]&&!(128&t[e+1])&&e<i;)e++;return 0===e?t:t.slice(e)};let r=this.r.toArray(),s=this.s.toArray();for(128&r[0]&&(r=[0].concat(r)),128&s[0]&&(s=[0].concat(s)),r=i(r),s=i(s);0===s[0]&&!(128&s[1]);)s=s.slice(1);let n=[2];e(n,r.length),n=n.concat(r),n.push(2),e(n,s.length);const a=n.concat(s);let o=[48];return e(o,a.length),o=o.concat(a),"hex"===t?jt(o):"base64"===t?Zt(o):o}toCompact(t,e,i){if(t<0||t>3)throw new Error("Invalid recovery param");if("boolean"!=typeof e)throw new Error("Invalid compressed param");let r=27+t;e&&(r+=4);let s=[r];return s=s.concat(this.r.toArray("be",32)),s=s.concat(this.s.toArray("be",32)),"hex"===i?jt(s):"base64"===i?Zt(s):s}RecoverPublicKey(t,e){const i=this.r,r=this.s,s=!!(1&t),n=t>>1,a=new Re,o=a.n,c=a.g,h=0!==n?i.add(o):i,u=Te.fromX(h,s);if(!u.mul(o).isInfinity())throw new Error("nR is not at infinity");const d=e.neg().umod(o),l=i.invm(o),f=l.mul(r).umod(o),p=l.mul(d).umod(o),g=c.mul(p).add(u.mul(f)),y=new $e(g);return y.validate(),y}CalculateRecoveryFactor(t,e){for(let i=0;i<4;i++){let r;try{r=this.RecoverPublicKey(i,e)}catch{continue}if(t.eq(r))return i}throw new Error("Unable to find valid recovery factor")}}class Le{K;V;constructor(t,e){const i=Wt(t,"hex"),r=Wt(e,"hex");if(32!==i.length)throw new Error("Entropy must be exactly 32 bytes (256 bits)");if(32!==r.length)throw new Error("Nonce must be exactly 32 bytes (256 bits)");const s=i.concat(r);this.K=new Array(32),this.V=new Array(32);for(let t=0;t<32;t++)this.K[t]=0,this.V[t]=1;this.update(s)}hmac(){return new W(this.K)}update(t){let e=this.hmac().update(this.V).update([0]);void 0!==t&&(e=e.update(t)),this.K=e.digest(),this.V=this.hmac().update(this.V).digest(),void 0!==t&&(this.K=this.hmac().update(this.V).update([1]).update(t).digest(),this.V=this.hmac().update(this.V).digest())}generate(t){let e=[];for(;e.length<t;)this.V=this.hmac().update(this.V).digest(),e=e.concat(this.V);const i=e.slice(0,t);return this.update(),jt(i)}}function Me(t,e,i=new Re){const r=8*t.byteLength()-i.n.bitLength();return r>0&&t.iushrn(r),!0!==e&&t.cmp(i.n)>=0?t.sub(i.n):t}function Fe(t){const e=t.toArray("be");let i=0n;for(let t=0;t<e.length;t++)i=i<<8n|BigInt(e[t]);return i}const Ue=new Re,De=Ue.n.byteLength(),He=Ue.n.subn(1),qe=le>>1n,Ve=(t,e,i=!1,r)=>{const s=Ue.n.bitLength();if(t.bitLength()>s)throw new Error(`ECDSA message is too large: expected <= ${s} bits. Callers must hash messages before signing.`);const n=Fe(t=Me(t)),o=Fe(e),c=e.toArray("be",De),h=t.toArray("be",De),u=new Le(c,h);for(let t=0;;t++){let e="function"==typeof r?r(t):a.isBN(r)?r:new a(u.generate(De),16);if(null==e)throw new Error("k is undefined");if(e=Me(e,!0),e.cmpn(1)<0||e.cmp(He)>0){if(a.isBN(r))throw new Error("Invalid fixed custom K value (must be >1 and <N-1)");continue}const s=Ue.g.mulCT(e);if(s.isInfinity()){if(a.isBN(r))throw new Error("Invalid fixed custom K value (k·G at infinity)");continue}const c=BigInt("0x"+s.getX().toString(16)),h=Ae(c);if(0n===h){if(a.isBN(r))throw new Error("Invalid fixed custom K value (r == 0)");continue}const d=BigInt("0x"+e.toString(16)),l=Oe(d),f=Ne(h,o),p=Ae(n+f);let g=Ne(l,p);if(0n===g){if(a.isBN(r))throw new Error("Invalid fixed custom K value (s == 0)");continue}i&&g>qe&&(g=le-g);const y=new a(h.toString(16),16),b=new a(g.toString(16),16);return new Be(y,b)}},Ke=(t,e,i)=>{const r=Ue.n.bitLength();if(t.bitLength()>r)return!1;const s=Fe(t);if(null==i.x||null==i.y)throw new Error("Invalid public key: missing coordinates.");const n={x:Fe(i.x),y:Fe(i.y)},a={r:Fe(e.r),s:Fe(e.s)},{r:o,s:c}=a,h=s;if(o<=0n||o>=le||c<=0n||c>=le)return!1;const u=Oe(c);if(0n===u)return!1;const d=Ne(h,u),l=Ne(o,u),f=_e(d,{x:Ie,y:ke}),p=_e(l,n),g=xe(f,p);if(0n===g.Z)return!1;const y=we(g.Z),b=be(y,y),m=be(g.X,b);return Ae(m)===o};class $e extends Te{static fromPrivateKey(t){const e=(new Re).g.mul(t);return new $e(e.x,e.y)}static fromString(t){const e=Te.fromString(t);return new $e(e.x,e.y)}static fromDER(t){const e=Te.fromDER(t);return new $e(e.x,e.y)}constructor(t,e=null,i=!0){if(t instanceof Te)super(t.getX(),t.getY());else{if(null===e&&i&&"string"==typeof t&&(66===t.length||130===t.length))throw new Error('You are using the "new PublicKey()" constructor with a DER hex string. You need to use "PublicKey.fromString()" instead.');super(t,e,i)}}deriveSharedSecret(t){if(!this.validate())throw new Error("Public key not valid for ECDH secret derivation");return this.mulCT(t)}verify(t,e,i){const r=new a(X(t,i),16);return Ke(r,e,this)}toDER(t){return"hex"===t?this.encode(!0,t):this.encode(!0)}toHash(t){const e=J(this.encode(!0));return"hex"===t?jt(e):e}toAddress(t=[0]){if("string"==typeof t)if("testnet"===t||"test"===t)t=[111];else{if("mainnet"!==t&&"main"!==t)throw new Error(`Invalid prefix ${t}`);t=[0]}return ie(this.toHash(),t)}deriveChild(t,e,i,r){let s;if("function"==typeof r){const e=r(t,this);void 0!==e?s=e:(s=this.deriveSharedSecret(t),"function"==typeof i&&i(t,this,s))}else s=this.deriveSharedSecret(t);const n=Wt(e,"utf8"),o=Z(s.encode(!0),n),c=(new Re).g.mul(new a(o)),h=this.add(c);return new $e(h.x,h.y)}static fromMsgHashAndCompactSignature(t,e,i){const r=Wt(e,i);if(65!==r.length)throw new Error("Invalid Compact Signature");const s=r[0];if(s<27||s>=35)throw new Error("Invalid Compact Byte");let n=r[0]-27;return n>3&&(n-=4),new Be(new a(r.slice(1,33)),new a(r.slice(33,65))).RecoverPublicKey(n,t)}}class je{_rand;getRandomValues(t,e){const i=new Uint8Array(e);return t.crypto.getRandomValues(i),Array.from(i)}constructor(){const t=()=>{throw new Error("No secure random number generator is available in this environment.")};if(this._rand=t,"undefined"==typeof globalThis||"function"!=typeof globalThis.crypto?.getRandomValues){if("undefined"!=typeof process&&"node"===process.release?.name)try{const t=require("crypto");if("function"==typeof t.randomBytes)return void(this._rand=e=>Array.from(t.randomBytes(e)))}catch(t){}"undefined"==typeof self||"function"!=typeof self.crypto?.getRandomValues?"undefined"==typeof window||"function"!=typeof window.crypto?.getRandomValues?this._rand=t:this._rand=t=>this.getRandomValues(window,t):this._rand=t=>this.getRandomValues(self,t)}else this._rand=t=>this.getRandomValues(globalThis,t)}generate(t){return this._rand(t)}}let ze=null;const We=t=>(null==ze&&(ze=new je),ze.generate(t));class Ge{x;y;constructor(t,e){const i=(new Re).p;this.x=t.umod(i),this.y=e.umod(i)}toString(){return ee(this.x.toArray())+"."+ee(this.y.toArray())}static fromString(t){const[e,i]=t.split(".");return new Ge(new a(te(e)),new a(te(i)))}}class Xe{points;threshold;constructor(t,e){this.points=t,this.threshold=e??t.length}static fromPrivateKey(t,e){const i=(new Re).p,r=[new Ge(new a(0),new a(t.toArray()))];for(let t=1;t<e;t++){const t=new a(We(32)).umod(i),e=new a(We(32)).umod(i);r.push(new Ge(t,e))}return new Xe(r)}valueAt(t){const e=(new Re).p;let i=new a(0);for(let r=0;r<this.threshold;r++){let s=this.points[r].y;for(let i=0;i<this.threshold;i++)if(r!==i){const n=this.points[i].x,a=this.points[r].x,o=t.sub(n).umod(e),c=a.sub(n).umod(e).invm(e),h=o.mul(c).umod(e);s=s.mul(h).umod(e)}i=i.add(s).umod(e)}return i}}class Ye{points;threshold;integrity;constructor(t,e,i){this.points=t,this.threshold=e,this.integrity=i}static fromBackupFormat(t){let e=0,i="";const r=t.map((t,r)=>{const s=t.split(".");if(4!==s.length)throw new Error("Invalid share format in share "+r.toString()+'. Expected format: "x.y.t.i" - received '+t);const[n,a,o,c]=s;if(void 0===o)throw new Error("Threshold not found in share "+r.toString());if(void 0===c)throw new Error("Integrity not found in share "+r.toString());const h=parseInt(o);if(0!==r&&e!==h)throw new Error("Threshold mismatch in share "+r.toString());if(0!==r&&i!==c)throw new Error("Integrity mismatch in share "+r.toString());return e=h,i=c,Ge.fromString([n,a].join("."))});return new Ye(r,e,i)}toBackupFormat(){return this.points.map(t=>t.toString()+"."+this.threshold.toString()+"."+this.integrity)}}class Je extends a{static fromRandom(){return new Je(We(32))}static fromString(t,e="hex"){return new Je(super.fromString(t,e).toArray())}static fromHex(t){return new Je(super.fromHex(t,"big"))}static fromWif(t,e=1){const i=re(t,void 0,e);if(33!==i.data.length)throw new Error("Invalid WIF length");if(1!==i.data[32])throw new Error("Invalid WIF padding");return new Je(i.data.slice(0,32))}constructor(t=0,e=10,i="be",r="apply"){if(t instanceof a?(super(),t.copy(this)):super(t,e,i),"nocheck"!==r){const t=this.checkInField();if(!t.inField){if("error"===r)throw new Error("Input is out of field");a.move(this,t.modN)}}}checkInField(){const t=new Re,e=this.mod(t.n);return{inField:0===this.cmp(e),modN:e}}isValid(){return this.checkInField().inField}sign(t,e,i=!0,r){const s=new a(X(t,e),16);return Ve(s,this,i,r)}verify(t,e,i){const r=new a(X(t,i),16);return Ke(r,e,this.toPublicKey())}toPublicKey(){const t=(new Re).g.mulCT(this);return new $e(t.x,t.y)}toWif(t=[128]){if(!this.isValid())throw new Error("Value is out of field");return ie([...this.toArray("be",32),1],t)}toAddress(t=[0]){return this.toPublicKey().toAddress(t)}toHex(){return super.toHex(32)}toString(t="hex",e=64){return super.toString(t,e)}deriveSharedSecret(t){if(!t.validate())throw new Error("Public key not valid for ECDH secret derivation");return t.mulCT(this)}deriveChild(t,e,i,r){let s;if("function"==typeof r){const e=r(this,t);void 0!==e?s=e:(s=this.deriveSharedSecret(t),"function"==typeof i&&i(this,t,s))}else s=this.deriveSharedSecret(t);const n=Wt(e,"utf8"),o=Z(s.encode(!0),n),c=new Re;return new Je(this.add(new a(o)).mod(c.n).toArray())}toKeyShares(t,e){if("number"!=typeof t||"number"!=typeof e)throw new Error("threshold and totalShares must be numbers");if(t<2)throw new Error("threshold must be at least 2");if(e<2)throw new Error("totalShares must be at least 2");if(t>e)throw new Error("threshold should be less than or equal to totalShares");const i=Xe.fromPrivateKey(this,t),r=[],s=new Set,n=new Re,o=We(64);for(let t=0;t<e;t++){let e,c=0;do{const i=[t,c,...We(32)],r=Q(o,i);if(e=new a(r).umod(n.p),c++,c>5)throw new Error("Failed to generate unique x coordinate after 5 attempts")}while(e.isZero()||s.has(e.toString()));s.add(e.toString());const h=i.valueAt(e);r.push(new Ge(e,h))}const c=this.toPublicKey().toHash("hex").slice(0,8);return new Ye(r,t,c)}toBackupShares(t,e){return this.toKeyShares(t,e).toBackupFormat()}static fromBackupShares(t){return Je.fromKeyShares(Ye.fromBackupFormat(t))}static fromKeyShares(t){const{points:e,threshold:i,integrity:r}=t;if(i<2)throw new Error("threshold must be at least 2");if(e.length<i)throw new Error(`At least ${i} shares are required to reconstruct the private key`);for(let t=0;t<i;t++)for(let r=t+1;r<i;r++)if(e[t].x.eq(e[r].x))throw new Error("Duplicate share detected, each must be unique.");const s=new Xe(e,i),n=new Je(s.valueAt(new a(0)).toArray());if(n.toPublicKey().toHash("hex").slice(0,8)!==r)throw new Error("Integrity hash mismatch");return n}}const Ze=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),Qe=[[0,0,0,0],[1,0,0,0],[2,0,0,0],[4,0,0,0],[8,0,0,0],[16,0,0,0],[32,0,0,0],[64,0,0,0],[128,0,0,0],[27,0,0,0],[54,0,0,0]].map(t=>new Uint8Array(t)),ti=new Uint8Array(256),ei=new Uint8Array(256);for(let t=0;t<256;t++){const e=255&(t<<1^(128&t?27:0));ti[t]=e,ei[t]=e^t}function ii(t){for(let e=0;e<4;e++){const i=t[0][e],r=t[1][e],s=t[2][e],n=t[3][e];t[0][e]=ti[i]^ei[r]^s^n,t[1][e]=i^ti[r]^ei[s]^n,t[2][e]=i^r^ti[s]^ei[n],t[3][e]=ei[i]^r^s^ti[n]}}function ri(t,e,i){for(let r=0;r<4;r++){const s=e[i+r];for(let e=0;e<4;e++)t[e][r]^=s[e]}}function si(t){for(let e=0;e<4;e++)for(let i=0;i<4;i++)t[e][i]=Ze[t[e][i]]}function ni(t){for(let e=0;e<4;e++)t[e]=Ze[t[e]]}function ai(t){const e=t[0];t[0]=t[1],t[1]=t[2],t[2]=t[3],t[3]=e}function oi(t){let e=t[1][0];t[1][0]=t[1][1],t[1][1]=t[1][2],t[1][2]=t[1][3],t[1][3]=e,e=t[2][0];const i=t[2][1];t[2][0]=t[2][2],t[2][1]=t[2][3],t[2][2]=e,t[2][3]=i,e=t[3][3],t[3][3]=t[3][2],t[3][2]=t[3][1],t[3][1]=t[3][0],t[3][0]=e}function ci(t,e){let i,r,s,n;const a=[[],[],[],[]],o=[],c=Array.from(e);if(16===c.length)n=11;else if(24===c.length)n=13;else{if(32!==c.length)throw new Error("Illegal key length: "+String(c.length));n=15}const h=function(t,e){const i=e.length/4,r=[];for(let t=0;t<e.length;t++)t%4==0&&r.push([]),r[t>>2].push(e[t]);for(let e=i;e<4*t;e++){r[e]=[];const t=r[e-1].slice();if(e%i===0){ai(t),ni(t);const r=Qe[e/i];for(let e=0;e<4;e++)t[e]^=r[e]}else i>6&&e%i===4&&ni(t);for(let s=0;s<4;s++)r[e][s]=r[e-i][s]^t[s]}return r}(n,c);for(let e=0;e<4;e++)a[0][e]=t[4*e],a[1][e]=t[4*e+1],a[2][e]=t[4*e+2],a[3][e]=t[4*e+3];for(ri(a,h,0),s=1;s<n;s++)si(a),oi(a),s+1<n&&ii(a),ri(a,h,4*s);for(i=0;i<4;i++)for(r=0;r<4;r++)o.push(a[r][i]);return o}const hi=function(t){if(t<0||t>Number.MAX_SAFE_INTEGER)throw new Error("getBytes64: value out of range");const e=Math.floor(t/4294967296),i=t>>>0;return[e>>>24&255,e>>>16&255,e>>>8&255,255&e,i>>>24&255,i>>>16&255,i>>>8&255,255&i]},ui=function(t){return new Uint8Array(t)},di=(()=>{const t=new Uint8Array(16);return t[0]=225,t})(),li=(...t)=>{let e=0;for(const i of t)e+=i.length;const i=new Uint8Array(e);let r=0;for(const e of t)i.set(e,r),r+=e.length;return i},fi=function(t){let e=0,i=0;for(let r=0;r<t.length;r++)i=e,e=1&t[r],t[r]=t[r]>>1,0!==i&&(t[r]=128|t[r]);return t},pi=function(t,e){const i=e.slice(),r=ui(16);for(let e=0;e<16;e++){const s=t[e];for(let t=7;t>=0;t--){const e=255&-(s>>t&1);for(let t=0;t<16;t++)r[t]^=i[t]&e;const n=255&-(1&i[15]);fi(i);for(let t=0;t<16;t++)i[t]^=di[t]&n}}return r},gi=function(t){const e=t.slice();for(let t=15;t>11&&(e[t]=e[t]+1&255,0===e[t]);t--);return e};function yi(t,e){let i=ui(16);const r=new Uint8Array(16);for(let s=0;s<t.length;s+=16){r.set(i);for(let e=0;e<16;e++)r[e]^=t[s+e]??0;i=pi(r,e)}return i}function bi(t,e,i){if(0===t.length)return new Uint8Array(0);const r=new Uint8Array(t.length);let s=e.slice(),n=0;const a=Math.ceil(t.length/16);for(let e=0;e<a;e++){const o=ci(s,i),c=Math.min(16,t.length-n);for(let e=0;e<c;e++)r[n]=t[n]^o[e],n++;e+1<a&&(s=gi(s))}return r}function mi(t){const e=8*t.length;let i;i=0===t.length?16:t.length%16==0?0:16-t.length%16;const r=16+t.length+i+16,s=new Uint8Array(r);let n=0;n+=16,s.set(t,n),n+=t.length,n+=i;const a=hi(0);s.set(a,n),n+=8;const o=hi(e);return s.set(o,n),s}class wi extends a{static fromRandom(){return new wi(We(32))}encrypt(t,e){const i=new Uint8Array(We(32)),r=new Uint8Array(Wt(t,e)),s=new Uint8Array(this.toArray("be",32)),{result:n,authenticationTag:a}=function(t,e,i){if(0===e.length)throw new Error("Initialization vector must not be empty");if(0===i.length)throw new Error("Key must not be empty");const r=new Uint8Array(ci(ui(16),i));let s;if(12===e.length)s=li(e,ui(3),new Uint8Array([1]));else{let t=e;t.length%16!=0&&(t=li(t,ui(16-t.length%16)));const i=hi(8*e.length);s=yi(li(t,ui(8),new Uint8Array(i)),r)}const n=bi(t,gi(s),i);return{result:n,authenticationTag:bi(yi(mi(n),r),s,i)}}(r,i,s),o=i.length+n.length+a.length,c=new Uint8Array(o);let h=0;return c.set(i,h),h+=i.length,c.set(n,h),h+=n.length,c.set(a,h),Jt(Array.from(c),e)}decrypt(t,e){const i=new Uint8Array(Wt(t,e));if(i.length<48)throw new Error("Ciphertext too short");const r=i.slice(0,32),s=i.length-16,n=function(t,e,i,r){if(0===t.length)throw new Error("Cipher text must not be empty");if(0===e.length)throw new Error("Initialization vector must not be empty");if(0===r.length)throw new Error("Key must not be empty");const s=new Uint8Array(ci(ui(16),r));let n;if(12===e.length)n=li(e,ui(3),new Uint8Array([1]));else{let t=e;t.length%16!=0&&(t=li(t,ui(16-t.length%16)));const i=hi(8*e.length);n=yi(li(t,ui(8),new Uint8Array(i)),s)}const a=bi(t,gi(n),r),o=bi(yi(mi(t),s),n,r);if(o.length!==i.length)return null;let c=0;for(let t=0;t<o.length;t++)c|=o[t]^i[t];return 0!==c?null:a}(i.slice(32,s),r,i.slice(s),new Uint8Array(this.toArray("be",32)));if(null===n)throw new Error("Decryption failed!");return Jt(Array.from(n),e)}}const vi={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SPLIT:127,OP_NUM2BIN:128,OP_BIN2NUM:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_NOP3:178,OP_NOP4:179,OP_SUBSTR:179,OP_NOP5:180,OP_LEFT:180,OP_NOP6:181,OP_RIGHT:181,OP_NOP7:182,OP_LSHIFTNUM:182,OP_NOP8:183,OP_RSHIFTNUM:183,OP_NOP9:184,OP_NOP10:185,OP_NOP11:186,OP_NOP12:187,OP_NOP13:188,OP_NOP14:189,OP_NOP15:190,OP_NOP16:191,OP_NOP17:192,OP_NOP18:193,OP_NOP19:194,OP_NOP20:195,OP_NOP21:196,OP_NOP22:197,OP_NOP23:198,OP_NOP24:199,OP_NOP25:200,OP_NOP26:201,OP_NOP27:202,OP_NOP28:203,OP_NOP29:204,OP_NOP30:205,OP_NOP31:206,OP_NOP32:207,OP_NOP33:208,OP_NOP34:209,OP_NOP35:210,OP_NOP36:211,OP_NOP37:212,OP_NOP38:213,OP_NOP39:214,OP_NOP40:215,OP_NOP41:216,OP_NOP42:217,OP_NOP43:218,OP_NOP44:219,OP_NOP45:220,OP_NOP46:221,OP_NOP47:222,OP_NOP48:223,OP_NOP49:224,OP_NOP50:225,OP_NOP51:226,OP_NOP52:227,OP_NOP53:228,OP_NOP54:229,OP_NOP55:230,OP_NOP56:231,OP_NOP57:232,OP_NOP58:233,OP_NOP59:234,OP_NOP60:235,OP_NOP61:236,OP_NOP62:237,OP_NOP63:238,OP_NOP64:239,OP_NOP65:240,OP_NOP66:241,OP_NOP67:242,OP_NOP68:243,OP_NOP69:244,OP_NOP70:245,OP_NOP71:246,OP_NOP72:247,OP_NOP73:248,OP_NOP77:252,OP_SMALLDATA:249,OP_SMALLINTEGER:250,OP_PUBKEYS:251,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};for(const t in vi)vi[vi[t]]=t;const Ii=vi,ki="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class Si{_chunks;parsed;rawBytesCache;hexCache;static fromASM(t){const e=[],i=t.split(" ");let r=0;for(;r<i.length;){const t=i[r];let s,n=0;if(t.startsWith("OP_")&&void 0!==Ii[t]&&(s=t,n=Ii[t]),"0"===t)n=0,e.push({op:n}),r+=1;else if("-1"===t)n=Ii.OP_1NEGATE,e.push({op:n}),r+=1;else if(void 0===s){let t=i[r];t.length%2!=0&&(t="0"+t);const s=Wt(t,"hex");if(Jt(s,"hex")!==t)throw new Error("invalid hex string in script");const a=s.length;a>=0&&a<Ii.OP_PUSHDATA1?n=a:a<Math.pow(2,8)?n=Ii.OP_PUSHDATA1:a<Math.pow(2,16)?n=Ii.OP_PUSHDATA2:a<Math.pow(2,32)&&(n=Ii.OP_PUSHDATA4),e.push({data:s,op:n}),r+=1}else n===Ii.OP_PUSHDATA1||n===Ii.OP_PUSHDATA2||n===Ii.OP_PUSHDATA4?(e.push({data:Wt(i[r+2],"hex"),op:n}),r+=3):(e.push({op:n}),r+=1)}return new Si(e)}static fromHex(t){if(0===t.length)return Si.fromBinary([]);if(t.length%2!=0)throw new Error("There is an uneven number of characters in the string which suggests it is not hex encoded.");if(!/^[0-9a-fA-F]+$/.test(t))throw new Error("Some elements in this string are not hex encoded.");const e=Wt(t,"hex"),i=Uint8Array.from(e);return new Si([],i,t.toLowerCase(),!1)}static fromBinary(t){const e=Uint8Array.from(t);return new Si([],e,void 0,!1)}constructor(t=[],e,i,r=!0){this._chunks=t,this.parsed=r,this.rawBytesCache=e,this.hexCache=i}get chunks(){return this.ensureParsed(),this._chunks}set chunks(t){this._chunks=t,this.parsed=!0,this.invalidateSerializationCaches()}ensureParsed(){this.parsed||(null!=this.rawBytesCache?this._chunks=Si.parseChunks(this.rawBytesCache):this._chunks=[],this.parsed=!0)}toASM(){let t="";for(let e=0;e<this.chunks.length;e++){const i=this.chunks[e];t+=this._chunkToString(i)}return t.slice(1)}toHex(){if(null!=this.hexCache)return this.hexCache;null==this.rawBytesCache&&(this.rawBytesCache=this.serializeChunksToBytes());const t=null!=ki?ki.from(this.rawBytesCache).toString("hex"):Jt(Array.from(this.rawBytesCache),"hex");return this.hexCache=t,t}toBinary(){return Array.from(this.toUint8Array())}toUint8Array(){return null==this.rawBytesCache&&(this.rawBytesCache=this.serializeChunksToBytes()),this.rawBytesCache}writeScript(t){return this.invalidateSerializationCaches(),this.chunks=this.chunks.concat(t.chunks),this}writeOpCode(t){return this.invalidateSerializationCaches(),this.chunks.push({op:t}),this}setChunkOpCode(t,e){return this.invalidateSerializationCaches(),this.chunks[t]={op:e},this}writeBn(t){if(this.invalidateSerializationCaches(),t.cmpn(0)===Ii.OP_0)this.chunks.push({op:Ii.OP_0});else if(0===t.cmpn(-1))this.chunks.push({op:Ii.OP_1NEGATE});else if(t.cmpn(1)>=0&&t.cmpn(16)<=0)this.chunks.push({op:t.toNumber()+Ii.OP_1-1});else{const e=t.toSm("little");this.writeBin(e)}return this}writeBin(t){let e;this.invalidateSerializationCaches();const i=t.length>0?t:void 0;if(t.length>0&&t.length<Ii.OP_PUSHDATA1)e=t.length;else if(0===t.length)e=Ii.OP_0;else if(t.length<Math.pow(2,8))e=Ii.OP_PUSHDATA1;else if(t.length<Math.pow(2,16))e=Ii.OP_PUSHDATA2;else{if(!(t.length<Math.pow(2,32)))throw new Error("You can't push that much data");e=Ii.OP_PUSHDATA4}return this.chunks.push({data:i,op:e}),this}writeNumber(t){return this.invalidateSerializationCaches(),this.writeBn(new a(t)),this}removeCodeseparators(){this.invalidateSerializationCaches();const t=[];for(let e=0;e<this.chunks.length;e++)this.chunks[e].op!==Ii.OP_CODESEPARATOR&&t.push(this.chunks[e]);return this.chunks=t,this}findAndDelete(t){this.invalidateSerializationCaches();const e=t.toUint8Array(),i=e.length;if(0===i)return this;const r=e[0]??0,s=t=>{if(t.op!==r)return!1;const s=t.data??[],n=s.length;if(0===n)return 1===i;if(t.op===Ii.OP_RETURN){if(i!==1+n)return!1;for(let t=0;t<n;t++)if(e[1+t]!==s[t])return!1;return!0}if(t.op<Ii.OP_PUSHDATA1){if(i!==1+n)return!1;for(let t=0;t<n;t++)if(e[1+t]!==s[t])return!1;return!0}if(t.op===Ii.OP_PUSHDATA1){if(i!==2+n)return!1;if(e[1]!==(255&n))return!1;for(let t=0;t<n;t++)if(e[2+t]!==s[t])return!1;return!0}if(t.op===Ii.OP_PUSHDATA2){if(i!==3+n)return!1;if(e[1]!==(255&n))return!1;if(e[2]!==(n>>8&255))return!1;for(let t=0;t<n;t++)if(e[3+t]!==s[t])return!1;return!0}if(t.op===Ii.OP_PUSHDATA4){if(i!==5+n)return!1;const t=n>>>0;if(e[1]!==(255&t))return!1;if(e[2]!==(t>>8&255))return!1;if(e[3]!==(t>>16&255))return!1;if(e[4]!==(t>>24&255))return!1;for(let t=0;t<n;t++)if(e[5+t]!==s[t])return!1;return!0}return!1};for(let t=0;t<this.chunks.length;)s(this.chunks[t])?this.chunks.splice(t,1):t++;return this}isPushOnly(){for(let t=0;t<this.chunks.length;t++)if(this.chunks[t].op>Ii.OP_16)return!1;return!0}isLockingScript(){throw new Error("Not implemented")}isUnlockingScript(){throw new Error("Not implemented")}static computeSerializedLength(t){let e=0;for(const i of t){if(e+=1,null==i.data)continue;const t=i.data.length;if(i.op===Ii.OP_RETURN){e+=t;break}i.op<Ii.OP_PUSHDATA1?e+=t:i.op===Ii.OP_PUSHDATA1?e+=1+t:i.op===Ii.OP_PUSHDATA2?e+=2+t:i.op===Ii.OP_PUSHDATA4&&(e+=4+t)}return e}serializeChunksToBytes(){const t=this.chunks,e=Si.computeSerializedLength(t),i=new Uint8Array(e);let r=0;for(let e=0;e<t.length;e++){const s=t[e];if(i[r++]=s.op,null!=s.data){if(s.op===Ii.OP_RETURN){i.set(s.data,r),r+=s.data.length;break}r=Si.writeChunkData(i,r,s.op,s.data)}}return i}invalidateSerializationCaches(){this.rawBytesCache=void 0,this.hexCache=void 0}static writeChunkData(t,e,i,r){const s=r.length;if(i<Ii.OP_PUSHDATA1)return t.set(r,e),e+s;if(i===Ii.OP_PUSHDATA1)return t[e++]=255&s,t.set(r,e),e+s;if(i===Ii.OP_PUSHDATA2)return t[e++]=255&s,t[e++]=s>>8&255,t.set(r,e),e+s;if(i===Ii.OP_PUSHDATA4){const i=s>>>0;return t[e++]=255&i,t[e++]=i>>8&255,t[e++]=i>>16&255,t[e++]=i>>24&255,t.set(r,e),e+s}return e}static parseChunks(t){const e=[],i=t.length;let r=0,s=0;for(;r<i;){const n=t[r++]??0;if(n===Ii.OP_RETURN&&0===s){e.push({op:n,data:Si.copyRange(t,r,i)});break}if(n===Ii.OP_IF||n===Ii.OP_NOTIF||n===Ii.OP_VERIF||n===Ii.OP_VERNOTIF?s++:n===Ii.OP_ENDIF&&s--,n>0&&n<Ii.OP_PUSHDATA1){const s=n,a=Math.min(r+s,i);e.push({data:Si.copyRange(t,r,a),op:n}),r=a}else if(n===Ii.OP_PUSHDATA1){const s=r<i?t[r++]??0:0,a=Math.min(r+s,i);e.push({data:Si.copyRange(t,r,a),op:n}),r=a}else if(n===Ii.OP_PUSHDATA2){const s=(t[r]??0)|(t[r+1]??0)<<8;r=Math.min(r+2,i);const a=Math.min(r+s,i);e.push({data:Si.copyRange(t,r,a),op:n}),r=a}else if(n===Ii.OP_PUSHDATA4){const s=((t[r]??0)|(t[r+1]??0)<<8|(t[r+2]??0)<<16|(t[r+3]??0)<<24)>>>0;r=Math.min(r+4,i);const a=Math.min(r+s,i);e.push({data:Si.copyRange(t,r,a),op:n}),r=a}else e.push({op:n})}return e}static copyRange(t,e,i){const r=Math.max(i-e,0),s=new Array(r);for(let i=0;i<r;i++)s[i]=t[e+i]??0;return s}_chunkToString(t){const e=t.op;let i="";return i=void 0===t.data?`${i} ${Ii[e]}`:`${i} ${jt(t.data)}`,i}}const Ei=new Uint8Array(0);class xi extends Be{static SIGHASH_ALL=1;static SIGHASH_NONE=2;static SIGHASH_SINGLE=3;static SIGHASH_CHRONICLE=32;static SIGHASH_FORKID=64;static SIGHASH_ANYONECANPAY=128;scope;static formatOTDA(t){const e=(t.scope&xi.SIGHASH_ANYONECANPAY)===xi.SIGHASH_ANYONECANPAY,i=(31&t.scope)===xi.SIGHASH_SINGLE,r=(31&t.scope)===xi.SIGHASH_NONE,s=(31&t.scope)===xi.SIGHASH_ALL||!i&&!r,n=new Si([...t.subscript.chunks]);n.findAndDelete((new Si).writeOpCode(Ii.OP_CODESEPARATOR));const a={sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,sequence:t.inputSequence,script:n.toBinary()},o=new se;function c(t){o.writeVarIntNum(t.length);for(const e of t)o.writeReverse(Wt(e.sourceTXID,"hex")),o.writeUInt32LE(e.sourceOutputIndex),o.writeVarIntNum(e.script.length),o.write(e.script),o.writeUInt32LE(e.sequence)}function h(t){o.writeVarIntNum(t.length);for(const e of t)o.writeUInt64LE(e.satoshis),o.writeVarIntNum(e.script.length),o.write(e.script)}o.writeInt32LE(t.transactionVersion);const u=(new Si).toBinary();if(e)e&&c([a]);else{const e=t.otherInputs.map(t=>({sourceTXID:t.sourceTXID??t.sourceTransaction?.id("hex")??"",sourceOutputIndex:t.sourceOutputIndex,sequence:i||r?0:t.sequence??4294967295,script:u}));e.splice(t.inputIndex,0,a),c(e)}if(s)h(t.outputs.map(t=>({satoshis:t.satoshis??0,script:t.lockingScript.toBinary()})));else if(i){const e=[];for(let i=0;i<t.inputIndex;i++)e.push({satoshis:-1,script:u});const i=t.outputs[t.inputIndex];void 0!==i&&e.push({satoshis:i.satoshis??0,script:i.lockingScript.toBinary()}),h(e)}else r&&h([]);return o.writeUInt32LE(t.lockTime),o.writeUInt32LE(t.scope>>>0),o.toUint8Array()}static formatBip143(t){const e=t.cache,i={sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,sequence:t.inputSequence},r=[...t.otherInputs];function s(e){const i=new se;if(void 0===e)for(const e of t.outputs){const t=e.satoshis??0;i.writeUInt64LE(t);const r=e.lockingScript?.toUint8Array()??Ei;i.writeVarIntNum(r.length),i.write(r)}else{const r=t.outputs[e];if(void 0===r)throw new Error(`Output at index ${e} does not exist`);const s=r.satoshis??0;i.writeUInt64LE(s);const n=r.lockingScript?.toUint8Array()??Ei;i.writeVarIntNum(n.length),i.write(n)}const r=i.toUint8Array();return Y(r)}r.splice(t.inputIndex,0,i);let n=new Array(32).fill(0),a=new Array(32).fill(0),o=new Array(32).fill(0);if(0===(t.scope&xi.SIGHASH_ANYONECANPAY)&&(null!=e?.hashPrevouts?n=e.hashPrevouts:(n=(()=>{const t=new se;for(const e of r){if(void 0===e.sourceTXID){if(null==e.sourceTransaction)throw new Error("Missing sourceTransaction for input");t.write(e.sourceTransaction.hash())}else t.writeReverse(Wt(e.sourceTXID,"hex"));t.writeUInt32LE(e.sourceOutputIndex)}const e=t.toUint8Array();return Y(e)})(),null!=e&&(e.hashPrevouts=n))),0===(t.scope&xi.SIGHASH_ANYONECANPAY)&&(31&t.scope)!==xi.SIGHASH_SINGLE&&(31&t.scope)!==xi.SIGHASH_NONE&&(null!=e?.hashSequence?a=e.hashSequence:(a=(()=>{const t=new se;for(const e of r){const i=e.sequence??4294967295;t.writeUInt32LE(i)}const e=t.toUint8Array();return Y(e)})(),null!=e&&(e.hashSequence=a))),(31&t.scope)!==xi.SIGHASH_SINGLE&&(31&t.scope)!==xi.SIGHASH_NONE)null!=e?.hashOutputsAll?o=e.hashOutputsAll:(o=s(),null!=e&&(e.hashOutputsAll=o));else if((31&t.scope)===xi.SIGHASH_SINGLE&&t.inputIndex<t.outputs.length){const i=t.inputIndex,r=e?.hashOutputsSingle?.get(i);null!=r?o=r:(o=s(i),null!=e&&(null==e.hashOutputsSingle&&(e.hashOutputsSingle=new Map),e.hashOutputsSingle.set(i,o)))}const c=new se;c.writeInt32LE(t.transactionVersion),c.write(n),c.write(a),c.writeReverse(Wt(t.sourceTXID,"hex")),c.writeUInt32LE(t.sourceOutputIndex);const h=t.subscript.toUint8Array();c.writeVarIntNum(h.length),c.write(h),c.writeUInt64LE(t.sourceSatoshis);const u=i.sequence;return c.writeUInt32LE(u),c.write(o),c.writeUInt32LE(t.lockTime),c.writeUInt32LE(t.scope>>>0),c.toUint8Array()}static format(t){return Array.from(this.formatBytes(t))}static formatBytes(t){const e=0!==(t.scope&xi.SIGHASH_FORKID),i=!0!==t.ignoreChronicle&&0!==(t.scope&xi.SIGHASH_CHRONICLE);return e&&!i?xi.formatBip143(t):!e||e&&i?xi.formatOTDA(t):new Uint8Array(0)}static fromChecksigFormat(t){if(0===t.length){const t=new a(1),e=new a(1);return new xi(t,e,1)}const e=t[t.length-1],i=t.slice(0,t.length-1),r=Be.fromDER(i);return new xi(r.r,r.s,e)}constructor(t,e,i){super(t,e),this.scope=i}hasLowS(){return!this.s.ltn(1)&&!this.s.gt(new a("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex"))}toChecksigFormat(){return[...this.toDER(),this.scope]}}class Pi{curve;constructor(){this.curve=new Re}generateProof(t,e,i,r){const s=Je.fromRandom(),n=s.toPublicKey(),a=i.mul(s),o=this.computeChallenge(e,i,r,a,n);return{R:n,SPrime:a,z:s.add(o.mul(t)).umod(this.curve.n)}}verifyProof(t,e,i,r){const{R:s,SPrime:n,z:a}=r,o=this.computeChallenge(t,e,i,n,s),c=this.curve.g.mul(a),h=s.add(t.mul(o));if(!c.eq(h))return!1;const u=e.mul(a),d=n.add(i.mul(o));return!!u.eq(d)}computeChallenge(t,e,i,r,s){const n=[...t.encode(!0),...e.encode(!0),...i.encode(!0),...r.encode(!0),...s.encode(!0)],o=X(n);return new a(o).umod(this.curve.n)}}BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5");class _i extends Si{isLockingScript(){return!0}isUnlockingScript(){return!1}}class Ai extends Si{isLockingScript(){return!1}isUnlockingScript(){return!0}}class Ni extends Error{txid;outputIndex;context;programCounter;stackState;altStackState;ifStackState;stackMem;altStackMem;constructor(t){const e=t.stackState.map(t=>null!=t&&void 0!==t.length?jt(t):null==t?"null/undef":"INVALID_STACK_ITEM").join(", "),i=t.altStackState.map(t=>null!=t&&void 0!==t.length?jt(t):null==t?"null/undef":"INVALID_STACK_ITEM").join(", "),r=`Context: ${t.context}, PC: ${t.programCounter}`,s=`Stack: [${e}] (len: ${t.stackState.length}, mem: ${t.stackMem})`,n=`AltStack: [${i}] (len: ${t.altStackState.length}, mem: ${t.altStackMem})`,a=`IfStack: [${t.ifStackState.join(", ")}]`;super(`Script evaluation error: ${t.message}\nTXID: ${t.txid}, OutputIdx: ${t.outputIndex}\n${r}\n${s}\n${n}\n${a}`),this.name=this.constructor.name,this.txid=t.txid,this.outputIndex=t.outputIndex,this.context=t.context,this.programCounter=t.programCounter,this.stackState=t.stackState.map(t=>t.slice()),this.altStackState=t.altStackState.map(t=>t.slice()),this.ifStackState=t.ifStackState.slice(),this.stackMem=t.stackMem,this.altStackMem=t.altStackMem}}const Oi=1073741824,Ti=Math.pow(2,31)-1,Ci=BigInt(Ti),Ri=Object.freeze(new a(-1).toScriptNum()),Bi=Object.freeze(Array.from({length:17},(t,e)=>Object.freeze(new a(e).toScriptNum())));function Li(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0}class Mi{sourceTXID;sourceOutputIndex;sourceSatoshis;lockingScript;transactionVersion;otherInputs;outputs;inputIndex;unlockingScript;inputSequence;lockTime;context;programCounter;lastCodeSeparator;stack;altStack;ifStack;memoryLimit;stackMem;altStackMem;isRelaxedOverride;sigHashCache;constructor(t){this.sourceTXID=t.sourceTXID,this.sourceOutputIndex=t.sourceOutputIndex,this.sourceSatoshis=t.sourceSatoshis,this.lockingScript=t.lockingScript,this.transactionVersion=t.transactionVersion,this.otherInputs=t.otherInputs,this.outputs=t.outputs,this.inputIndex=t.inputIndex,this.unlockingScript=t.unlockingScript,this.inputSequence=t.inputSequence,this.lockTime=t.lockTime,this.memoryLimit=t.memoryLimit??32e6,this.isRelaxedOverride=!0===t.isRelaxed,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0,this.sigHashCache={hashOutputsSingle:new Map},this.reset()}isRelaxed(){return this.isRelaxedOverride||this.transactionVersion>1}reset(){this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0,this.sigHashCache={hashOutputsSingle:new Map}}ensureStackMem(t){this.stackMem+t>this.memoryLimit&&this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}ensureAltStackMem(t){this.altStackMem+t>this.memoryLimit&&this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}pushStack(t){this.ensureStackMem(t.length),this.stack.push(t),this.stackMem+=t.length}pushStackCopy(t){this.ensureStackMem(t.length);const e=t.slice();this.stack.push(e),this.stackMem+=e.length}popStack(){0===this.stack.length&&this.scriptEvaluationError("Attempted to pop from an empty stack.");const t=this.stack.pop();return this.stackMem-=t.length,t}stackTop(t=-1){return(0===this.stack.length||this.stack.length<Math.abs(t)||t>=0&&t>=this.stack.length)&&this.scriptEvaluationError(`Stack underflow accessing element at index ${t}. Stack length is ${this.stack.length}.`),this.stack[this.stack.length+t]}pushAltStack(t){this.ensureAltStackMem(t.length),this.altStack.push(t),this.altStackMem+=t.length}popAltStack(){0===this.altStack.length&&this.scriptEvaluationError("Attempted to pop from an empty alt stack.");const t=this.altStack.pop();return this.altStackMem-=t.length,t}checkSignatureEncoding(t){if(0===t.length)return!0;if(!function(t){if(t.length<9||t.length>73)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-3)return!1;const e=t[2],i=t[3];if(2!==e)return!1;if(0===i)return!1;if(5+i>=t.length)return!1;const r=4+i,s=t[r],n=t[r+1];if(2!==s)return!1;if(0===n)return!1;if(128&t[4])return!1;if(i>1&&0===t[4]&&!(128&t[5]))return!1;const a=r+2;return!(128&t[a]||n>1&&0===t[a]&&!(128&t[a+1])||i+n+7!==t.length)}(t))return this.scriptEvaluationError("The signature format is invalid."),!1;try{const e=xi.fromChecksigFormat(t);if(!this.isRelaxed()&&!e.hasLowS())return this.scriptEvaluationError("The signature must have a low S value."),!1}catch(t){return this.scriptEvaluationError("The signature format is invalid."),!1}return!0}checkPublicKeyEncoding(t){if(0===t.length)return this.scriptEvaluationError("Public key is empty."),!1;if(t.length<33)return this.scriptEvaluationError("The public key is too short, it must be at least 33 bytes."),!1;if(4===t[0]){if(65!==t.length)return this.scriptEvaluationError("The non-compressed public key must be 65 bytes."),!1}else{if(2!==t[0]&&3!==t[0])return this.scriptEvaluationError("The public key is in an unknown format."),!1;if(33!==t.length)return this.scriptEvaluationError("The compressed public key must be 33 bytes."),!1}try{$e.fromDER(t)}catch(t){return this.scriptEvaluationError("The public key is in an unknown format."),!1}return!0}verifySignature(t,e,i){const r=xi.formatBytes({sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,transactionVersion:this.transactionVersion,otherInputs:this.otherInputs,outputs:this.outputs,inputIndex:this.inputIndex,subscript:i,inputSequence:this.inputSequence,lockTime:this.lockTime,scope:t.scope,cache:this.sigHashCache}),s=new a(Y(r));return Ke(s,t,e)}step(){if(this.stackMem>this.memoryLimit)return this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;if(this.altStackMem>this.memoryLimit)return this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;"UnlockingScript"===this.context&&this.programCounter>=this.unlockingScript.chunks.length&&(this.context="LockingScript",this.programCounter=0);const t="UnlockingScript"===this.context?this.unlockingScript:this.lockingScript;if(this.programCounter>=t.chunks.length)return!1;const e=t.chunks[this.programCounter],i=e.op;void 0===i&&this.scriptEvaluationError(`Missing opcode in ${this.context} at pc=${this.programCounter}.`),Array.isArray(e.data)&&e.data.length>Oi&&this.scriptEvaluationError(`Data push > 1073741824 bytes (pc=${this.programCounter}).`);const r=!this.ifStack.includes(!1);if(r&&i>=0&&i<=Ii.OP_PUSHDATA4)this.isRelaxed()||function(t){const e=t.data,i=t.op;return!(Array.isArray(e)&&(0===e.length?i!==Ii.OP_0:1===e.length&&e[0]>=1&&e[0]<=16?i!==Ii.OP_1+(e[0]-1):1===e.length&&129===e[0]?i!==Ii.OP_1NEGATE:e.length<=75?i!==e.length:e.length<=255?i!==Ii.OP_PUSHDATA1:e.length<=65535&&i!==Ii.OP_PUSHDATA2))}(e)||this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`),this.pushStack(Array.isArray(e.data)?e.data:[]);else if(r||i>=Ii.OP_IF&&i<=Ii.OP_ENDIF){let t,e,n,o,c,h,u,d,l,f,p,g,y,b,m,w,v,I,k,S,E,x,P,_,A,N;switch(i){case Ii.OP_VER:this.pushStackCopy(new a(this.transactionVersion).toScriptNum());break;case Ii.OP_SUBSTR:{this.stack.length<3&&this.scriptEvaluationError("OP_SUBSTR requires at least three items to be on the stack.");const e=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber(),i=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber();t=this.popStack();const r=t.length;(i<0||i>=r||e<0||e>r-i)&&this.scriptEvaluationError(`OP_SUBSTR offset (${i}) must be in range [0, ${r}) and length (${e}) must be in range [0, ${r-i}]`),this.pushStack(t.slice(i,i+e));break}case Ii.OP_LEFT:{this.stack.length<2&&this.scriptEvaluationError("OP_LEFT requires at least two items to be on the stack.");const e=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber();t=this.popStack();const i=t.length;(e<0||e>i)&&this.scriptEvaluationError(`OP_LEFT length (${e}) must be in range [0, ${i}]`),this.pushStack(t.slice(0,e));break}case Ii.OP_RIGHT:{this.stack.length<2&&this.scriptEvaluationError("OP_RIGHT requires at least two items to be on the stack.");const e=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber();t=this.popStack();const i=t.length;(e<0||e>i)&&this.scriptEvaluationError(`OP_RIGHT length (${e}) must be in range [0, ${i}]`),this.pushStack(t.slice(i-e,e));break}case Ii.OP_LSHIFTNUM:{this.stack.length<2&&this.scriptEvaluationError("OP_LSHIFTNUM requires at least two items to be on the stack.");const t=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();t<0&&this.scriptEvaluationError("OP_LSHIFTNUM bits to shift must not be negative.");const e=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt(),i=new a(e<<t);this.pushStack(i.toScriptNum());break}case Ii.OP_RSHIFTNUM:{this.stack.length<2&&this.scriptEvaluationError("OP_RSHIFTNUM requires at least two items to be on the stack.");const t=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();t<0&&this.scriptEvaluationError("OP_RSHIFTNUM bits to shift must not be negative.");const e=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();let i;i=new a(e<0?-(-e>>t):e>>t),this.pushStack(i.toScriptNum());break}case Ii.OP_1NEGATE:this.pushStackCopy(Ri);break;case Ii.OP_0:this.pushStackCopy(Bi[0]);break;case Ii.OP_1:case Ii.OP_2:case Ii.OP_3:case Ii.OP_4:case Ii.OP_5:case Ii.OP_6:case Ii.OP_7:case Ii.OP_8:case Ii.OP_9:case Ii.OP_10:case Ii.OP_11:case Ii.OP_12:case Ii.OP_13:case Ii.OP_14:case Ii.OP_15:case Ii.OP_16:g=i-(Ii.OP_1-1),this.pushStackCopy(Bi[g]);break;case Ii.OP_NOP:case Ii.OP_NOP1:case Ii.OP_NOP2:case Ii.OP_NOP3:case Ii.OP_NOP7:case Ii.OP_NOP8:case Ii.OP_NOP9:case Ii.OP_NOP10:case Ii.OP_NOP11:case Ii.OP_NOP12:case Ii.OP_NOP13:case Ii.OP_NOP14:case Ii.OP_NOP15:case Ii.OP_NOP16:case Ii.OP_NOP17:case Ii.OP_NOP18:case Ii.OP_NOP19:case Ii.OP_NOP20:case Ii.OP_NOP21:case Ii.OP_NOP22:case Ii.OP_NOP23:case Ii.OP_NOP24:case Ii.OP_NOP25:case Ii.OP_NOP26:case Ii.OP_NOP27:case Ii.OP_NOP28:case Ii.OP_NOP29:case Ii.OP_NOP30:case Ii.OP_NOP31:case Ii.OP_NOP32:case Ii.OP_NOP33:case Ii.OP_NOP34:case Ii.OP_NOP35:case Ii.OP_NOP36:case Ii.OP_NOP37:case Ii.OP_NOP38:case Ii.OP_NOP39:case Ii.OP_NOP40:case Ii.OP_NOP41:case Ii.OP_NOP42:case Ii.OP_NOP43:case Ii.OP_NOP44:case Ii.OP_NOP45:case Ii.OP_NOP46:case Ii.OP_NOP47:case Ii.OP_NOP48:case Ii.OP_NOP49:case Ii.OP_NOP50:case Ii.OP_NOP51:case Ii.OP_NOP52:case Ii.OP_NOP53:case Ii.OP_NOP54:case Ii.OP_NOP55:case Ii.OP_NOP56:case Ii.OP_NOP57:case Ii.OP_NOP58:case Ii.OP_NOP59:case Ii.OP_NOP60:case Ii.OP_NOP61:case Ii.OP_NOP62:case Ii.OP_NOP63:case Ii.OP_NOP64:case Ii.OP_NOP65:case Ii.OP_NOP66:case Ii.OP_NOP67:case Ii.OP_NOP68:case Ii.OP_NOP69:case Ii.OP_NOP70:case Ii.OP_NOP71:case Ii.OP_NOP72:case Ii.OP_NOP73:case Ii.OP_NOP77:break;case Ii.OP_VERIF:case Ii.OP_VERNOTIF:b=!1,r&&(this.stack.length<1&&this.scriptEvaluationError("OP_VERIF and OP_VERNOTIF require at least one item on the stack when they are used!"),n=new a(this.transactionVersion).toScriptNum(),e=this.popStack(),b=Li(e,n),i===Ii.OP_VERNOTIF&&(b=!b)),this.ifStack.push(b);break;case Ii.OP_IF:case Ii.OP_NOTIF:b=!1,r&&(this.stack.length<1&&this.scriptEvaluationError("OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),t=this.popStack(),b=this.castToBool(t),i===Ii.OP_NOTIF&&(b=!b)),this.ifStack.push(b);break;case Ii.OP_ELSE:0===this.ifStack.length&&this.scriptEvaluationError("OP_ELSE requires a preceeding OP_IF."),this.ifStack[this.ifStack.length-1]=!this.ifStack[this.ifStack.length-1];break;case Ii.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop();break;case Ii.OP_VERIFY:this.stack.length<1&&this.scriptEvaluationError("OP_VERIFY requires at least one item to be on the stack."),e=this.stackTop(),b=this.castToBool(e),b||this.scriptEvaluationError("OP_VERIFY requires the top stack value to be truthy."),this.popStack();break;case Ii.OP_RETURN:"UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.ifStack=[],this.programCounter--;break;case Ii.OP_TOALTSTACK:this.stack.length<1&&this.scriptEvaluationError("OP_TOALTSTACK requires at oeast one item to be on the stack."),this.pushAltStack(this.popStack());break;case Ii.OP_FROMALTSTACK:this.altStack.length<1&&this.scriptEvaluationError("OP_FROMALTSTACK requires at least one item to be on the stack."),this.pushStack(this.popAltStack());break;case Ii.OP_2DROP:this.stack.length<2&&this.scriptEvaluationError("OP_2DROP requires at least two items to be on the stack."),this.popStack(),this.popStack();break;case Ii.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),e=this.stackTop(-2),n=this.stackTop(-1),this.pushStackCopy(e),this.pushStackCopy(n);break;case Ii.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),e=this.stackTop(-3),n=this.stackTop(-2),o=this.stackTop(-1),this.pushStackCopy(e),this.pushStackCopy(n),this.pushStackCopy(o);break;case Ii.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),e=this.stackTop(-4),n=this.stackTop(-3),this.pushStackCopy(e),this.pushStackCopy(n);break;case Ii.OP_2ROT:{this.stack.length<6&&this.scriptEvaluationError("OP_2ROT requires at least six items to be on the stack.");const t=this.popStack(),e=this.popStack(),i=this.popStack(),r=this.popStack(),s=this.popStack(),n=this.popStack();this.pushStack(r),this.pushStack(i),this.pushStack(e),this.pushStack(t),this.pushStack(n),this.pushStack(s);break}case Ii.OP_2SWAP:{this.stack.length<4&&this.scriptEvaluationError("OP_2SWAP requires at least four items to be on the stack.");const t=this.popStack(),e=this.popStack(),i=this.popStack(),r=this.popStack();this.pushStack(e),this.pushStack(t),this.pushStack(r),this.pushStack(i);break}case Ii.OP_IFDUP:this.stack.length<1&&this.scriptEvaluationError("OP_IFDUP requires at least one item to be on the stack."),e=this.stackTop(),this.castToBool(e)&&this.pushStackCopy(e);break;case Ii.OP_DEPTH:this.pushStack(new a(this.stack.length).toScriptNum());break;case Ii.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),this.popStack();break;case Ii.OP_DUP:this.stack.length<1&&this.scriptEvaluationError("OP_DUP requires at least one item to be on the stack."),this.pushStackCopy(this.stackTop());break;case Ii.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),n=this.popStack(),this.popStack(),this.pushStack(n);break;case Ii.OP_OVER:this.stack.length<2&&this.scriptEvaluationError("OP_OVER requires at least two items to be on the stack."),this.pushStackCopy(this.stackTop(-2));break;case Ii.OP_PICK:case Ii.OP_ROLL:{this.stack.length<2&&this.scriptEvaluationError(`${Ii[i]} requires at least two items to be on the stack.`),d=a.fromScriptNum(this.popStack(),!this.isRelaxed());const t=d.toBigInt();(t<0n||t>=BigInt(this.stack.length))&&this.scriptEvaluationError(`${Ii[i]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);const e=Number(t),r=this.stack[this.stack.length-1-e];i===Ii.OP_ROLL?(this.stack.splice(this.stack.length-1-e,1),this.stackMem-=r.length,this.pushStack(r)):this.pushStackCopy(r);break}case Ii.OP_ROT:this.stack.length<3&&this.scriptEvaluationError("OP_ROT requires at least three items to be on the stack."),u=this.popStack(),h=this.popStack(),c=this.popStack(),this.pushStack(h),this.pushStack(u),this.pushStack(c);break;case Ii.OP_SWAP:this.stack.length<2&&this.scriptEvaluationError("OP_SWAP requires at least two items to be on the stack."),h=this.popStack(),c=this.popStack(),this.pushStack(h),this.pushStack(c);break;case Ii.OP_TUCK:this.stack.length<2&&this.scriptEvaluationError("OP_TUCK requires at least two items to be on the stack."),e=this.stackTop(-1),this.ensureStackMem(e.length),this.stack.splice(this.stack.length-2,0,e.slice()),this.stackMem+=e.length;break;case Ii.OP_SIZE:this.stack.length<1&&this.scriptEvaluationError("OP_SIZE requires at least one item to be on the stack."),this.pushStack(new a(this.stackTop().length).toScriptNum());break;case Ii.OP_AND:case Ii.OP_OR:case Ii.OP_XOR:{this.stack.length<2&&this.scriptEvaluationError(`${Ii[i]} requires at least two items on the stack.`),n=this.popStack(),e=this.popStack(),e.length!==n.length&&this.scriptEvaluationError(`${Ii[i]} requires the top two stack items to be the same size.`);const t=new Array(e.length);for(let r=0;r<e.length;r++)i===Ii.OP_AND?t[r]=e[r]&n[r]:i===Ii.OP_OR?t[r]=e[r]|n[r]:t[r]=e[r]^n[r];this.pushStack(t);break}case Ii.OP_INVERT:{this.stack.length<1&&this.scriptEvaluationError("OP_INVERT requires at least one item to be on the stack."),t=this.popStack();const e=new Array(t.length);for(let i=0;i<t.length;i++)e[i]=255&~t[i];this.pushStack(e);break}case Ii.OP_LSHIFT:case Ii.OP_RSHIFT:{this.stack.length<2&&this.scriptEvaluationError(`${Ii[i]} requires at least two items to be on the stack.`),f=a.fromScriptNum(this.popStack(),!this.isRelaxed()),e=this.popStack();const t=f.toBigInt();if(t<0n&&this.scriptEvaluationError(`${Ii[i]} requires the top item on the stack not to be negative.`),0===e.length){this.pushStack([]);break}let r;l=new a(e),r=i===Ii.OP_LSHIFT?l.ushln(t):l.ushrn(t);const s=r.toArray("be",e.length);this.pushStack(s);break}case Ii.OP_EQUAL:case Ii.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${Ii[i]} requires at least two items to be on the stack.`),n=this.popStack(),e=this.popStack(),b=Li(e,n),this.pushStack(b?[1]:[]),i===Ii.OP_EQUALVERIFY&&(b||this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."),this.popStack());break;case Ii.OP_1ADD:case Ii.OP_1SUB:case Ii.OP_2MUL:case Ii.OP_2DIV:case Ii.OP_NEGATE:case Ii.OP_ABS:case Ii.OP_NOT:case Ii.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${Ii[i]} requires at least one item to be on the stack.`),d=a.fromScriptNum(this.popStack(),!this.isRelaxed()),i){case Ii.OP_1ADD:d=d.add(new a(1));break;case Ii.OP_1SUB:d=d.sub(new a(1));break;case Ii.OP_2MUL:d=d.mul(new a(2));break;case Ii.OP_2DIV:d=d.div(new a(2));break;case Ii.OP_NEGATE:d=d.neg();break;case Ii.OP_ABS:d.isNeg()&&(d=d.neg());break;case Ii.OP_NOT:d=new a(0===d.cmpn(0)?1:0);break;case Ii.OP_0NOTEQUAL:d=new a(0!==d.cmpn(0)?1:0)}this.pushStack(d.toScriptNum());break;case Ii.OP_ADD:case Ii.OP_SUB:case Ii.OP_MUL:case Ii.OP_DIV:case Ii.OP_MOD:case Ii.OP_BOOLAND:case Ii.OP_BOOLOR:case Ii.OP_NUMEQUAL:case Ii.OP_NUMEQUALVERIFY:case Ii.OP_NUMNOTEQUAL:case Ii.OP_LESSTHAN:case Ii.OP_GREATERTHAN:case Ii.OP_LESSTHANOREQUAL:case Ii.OP_GREATERTHANOREQUAL:case Ii.OP_MIN:case Ii.OP_MAX:{this.stack.length<2&&this.scriptEvaluationError(`${Ii[i]} requires at least two items to be on the stack.`),n=this.popStack(),e=this.popStack(),f=a.fromScriptNum(n,!this.isRelaxed()),l=a.fromScriptNum(e,!this.isRelaxed());let t=0;switch(i){case Ii.OP_MUL:t=l.byteLength()+f.byteLength();break;case Ii.OP_ADD:case Ii.OP_SUB:t=Math.max(l.byteLength(),f.byteLength())+1;break;default:t=Math.max(l.byteLength(),f.byteLength())}this.ensureStackMem(t);let r=new a(0);switch(i){case Ii.OP_ADD:r=l.add(f);break;case Ii.OP_SUB:r=l.sub(f);break;case Ii.OP_MUL:r=l.mul(f);break;case Ii.OP_DIV:0===f.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),r=l.div(f);break;case Ii.OP_MOD:0===f.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),r=l.mod(f);break;case Ii.OP_BOOLAND:r=new a(0!==l.cmpn(0)&&0!==f.cmpn(0)?1:0);break;case Ii.OP_BOOLOR:r=new a(0!==l.cmpn(0)||0!==f.cmpn(0)?1:0);break;case Ii.OP_NUMEQUAL:case Ii.OP_NUMEQUALVERIFY:r=new a(0===l.cmp(f)?1:0);break;case Ii.OP_NUMNOTEQUAL:r=new a(0!==l.cmp(f)?1:0);break;case Ii.OP_LESSTHAN:r=new a(l.cmp(f)<0?1:0);break;case Ii.OP_GREATERTHAN:r=new a(l.cmp(f)>0?1:0);break;case Ii.OP_LESSTHANOREQUAL:r=new a(l.cmp(f)<=0?1:0);break;case Ii.OP_GREATERTHANOREQUAL:r=new a(l.cmp(f)>=0?1:0);break;case Ii.OP_MIN:r=l.cmp(f)<0?l:f;break;case Ii.OP_MAX:r=l.cmp(f)>0?l:f}this.pushStack(r.toScriptNum()),i===Ii.OP_NUMEQUALVERIFY&&(this.castToBool(this.stackTop())||this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."),this.popStack());break}case Ii.OP_WITHIN:this.stack.length<3&&this.scriptEvaluationError("OP_WITHIN requires at least three items to be on the stack."),p=a.fromScriptNum(this.popStack(),!this.isRelaxed()),f=a.fromScriptNum(this.popStack(),!this.isRelaxed()),l=a.fromScriptNum(this.popStack(),!this.isRelaxed()),b=l.cmp(f)>=0&&l.cmp(p)<0,this.pushStack(b?[1]:[]);break;case Ii.OP_RIPEMD160:case Ii.OP_SHA1:case Ii.OP_SHA256:case Ii.OP_HASH160:case Ii.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${Ii[i]} requires at least one item to be on the stack.`),t=this.popStack();let e=[];i===Ii.OP_RIPEMD160?(s=t,e=(new $).update(s,void 0).digest()):i===Ii.OP_SHA1?e=(t=>(new z).update(t,void 0).digest())(t):i===Ii.OP_SHA256?e=X(t):i===Ii.OP_HASH160?e=J(t):i===Ii.OP_HASH256&&(e=Y(t)),this.pushStack(e);break}case Ii.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case Ii.OP_CHECKSIG:case Ii.OP_CHECKSIGVERIFY:if(this.stack.length<2&&this.scriptEvaluationError(`${Ii[i]} requires at least two items to be on the stack.`),I=this.popStack(),v=this.popStack(),this.checkSignatureEncoding(v)&&this.checkPublicKeyEncoding(I)||this.scriptEvaluationError(`${Ii[i]} requires correct encoding for the public key and signature.`),m=!1,v.length>0)try{k=xi.fromChecksigFormat(v);const t=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);w=new Si(t),w.findAndDelete((new Si).writeBin(v)),S=$e.fromDER(I),m=this.verifySignature(k,S,w)}catch(t){m=!1}this.pushStack(m?[1]:[]),i===Ii.OP_CHECKSIGVERIFY&&(m||this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."),this.popStack());break;case Ii.OP_CHECKMULTISIG:case Ii.OP_CHECKMULTISIGVERIFY:{E=1,this.stack.length<E&&this.scriptEvaluationError(`${Ii[i]} requires at least 1 item for nKeys.`);const t=a.fromScriptNum(this.stackTop(-E),!this.isRelaxed()).toBigInt();(t<0n||t>Ci)&&this.scriptEvaluationError(`${Ii[i]} requires a key count between 0 and ${Ti}.`),_=Number(t);const e=_;x=++E,E+=_,this.stack.length<E&&this.scriptEvaluationError(`${Ii[i]} stack too small for nKeys and keys. Need ${E}, have ${this.stack.length}.`);const r=a.fromScriptNum(this.stackTop(-E),!this.isRelaxed()).toBigInt();(r<0n||r>BigInt(_))&&this.scriptEvaluationError(`${Ii[i]} requires the number of signatures to be no greater than the number of keys.`),A=Number(r);const s=A;P=++E,E+=A,this.stack.length<E&&this.scriptEvaluationError(`${Ii[i]} stack too small for N, keys, M, sigs, and dummy. Need ${E}, have ${this.stack.length}.`);const n=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);w=new Si(n);for(let t=0;t<A;t++)v=this.stackTop(-P-t),w.findAndDelete((new Si).writeBin(v));for(m=!0;m&&A>0;){if(0===_){m=!1;break}if(v=this.stackTop(-P),I=this.stackTop(-x),this.checkSignatureEncoding(v)&&this.checkPublicKeyEncoding(I)||this.scriptEvaluationError(`${Ii[i]} requires correct encoding for the public key and signature.`),N=!1,v.length>0)try{k=xi.fromChecksigFormat(v),S=$e.fromDER(I),N=this.verifySignature(k,S,w)}catch(t){N=!1}N&&(P++,A--),x++,_--,A>_&&(m=!1)}let o=1+e+1+s+1-1;for(;o>0;)this.popStack(),o--;this.stack.length<1&&this.scriptEvaluationError(`${Ii[i]} requires an extra item (dummy) to be on the stack.`);const c=this.popStack();!this.isRelaxed()&&c.length>0&&this.scriptEvaluationError(`${Ii[i]} requires the extra stack item (dummy) to be empty.`),this.pushStack(m?[1]:[]),i===Ii.OP_CHECKMULTISIGVERIFY&&(m||this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),this.popStack());break}case Ii.OP_CAT:{this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),n=this.popStack(),e=this.popStack();const t=e.concat(n);t.length>Oi&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),this.pushStack(t);break}case Ii.OP_SPLIT:{this.stack.length<2&&this.scriptEvaluationError("OP_SPLIT requires at least two items to be on the stack.");const t=this.popStack(),e=this.popStack(),i=a.fromScriptNum(t,!this.isRelaxed()).toBigInt();(i<0n||i>BigInt(e.length))&&this.scriptEvaluationError("OP_SPLIT requires the first stack item to be a non-negative number less than or equal to the size of the second-from-top stack item.");const r=Number(i);this.pushStack(e.slice(0,r)),this.pushStack(e.slice(r));break}case Ii.OP_NUM2BIN:{this.stack.length<2&&this.scriptEvaluationError("OP_NUM2BIN requires at least two items to be on the stack.");const t=a.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();(t>BigInt(Oi)||t<0n)&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes or negative size."),y=Number(t);let e=this.popStack();if(e=ae(e),e.length>y&&this.scriptEvaluationError("OP_NUM2BIN requires that the size expressed in the top stack item is large enough to hold the value expressed in the second-from-top stack item."),e.length===y){this.pushStack(e);break}const i=new Array(y).fill(0);let r=0;e.length>0&&(r=128&e[e.length-1],e[e.length-1]&=127);for(let t=0;t<e.length;t++)i[t]=e[t];0!==r&&(i[y-1]|=128),this.pushStack(i);break}case Ii.OP_BIN2NUM:{this.stack.length<1&&this.scriptEvaluationError("OP_BIN2NUM requires at least one item to be on the stack."),e=this.popStack();const t=ae(e);(function(t,e=Number.MAX_SAFE_INTEGER){return!(t.length>e||t.length>0&&!(127&t[t.length-1]||!(t.length<=1)&&128&t[t.length-2]))})(t)||this.scriptEvaluationError("OP_BIN2NUM requires that the resulting number is valid."),this.pushStack(t);break}default:this.scriptEvaluationError(`Invalid opcode ${i} (pc=${this.programCounter}).`)}}var s;return this.programCounter++,!0}validate(){for(this.isRelaxed()||this.unlockingScript.isPushOnly()||this.scriptEvaluationError("Unlocking scripts can only contain push operations, and no other opcodes.");this.step()&&!("LockingScript"===this.context&&this.programCounter>=this.lockingScript.chunks.length););return this.ifStack.length>0&&this.scriptEvaluationError("Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the script."),this.isRelaxed()||1!==this.stack.length&&this.scriptEvaluationError(`The clean stack rule requires exactly one item to be on the stack after script execution, found ${this.stack.length}.`),0===this.stack.length?this.scriptEvaluationError("The top stack element must be truthy after script evaluation (stack is empty)."):this.castToBool(this.stackTop())||this.scriptEvaluationError("The top stack element must be truthy after script evaluation."),!0}castToBool(t){if(0===t.length)return!1;for(let e=0;e<t.length;e++)if(0!==t[e])return!(e===t.length-1&&128===t[e]);return!1}scriptEvaluationError(t){throw new Ni({message:t,txid:this.sourceTXID,outputIndex:this.sourceOutputIndex,context:this.context,programCounter:this.programCounter,stackState:this.stack,altStackState:this.altStack,ifStackState:this.ifStack,stackMem:this.stackMem,altStackMem:this.altStackMem})}}class Fi{lock(t){let e;if("string"==typeof t){const i=re(t);if(0!==i.prefix[0]&&111!==i.prefix[0])throw new Error("only P2PKH is supported");e=i.data}else e=t;if(20!==e.length)throw new Error("P2PKH hash length must be 20 bytes");return new _i([{op:Ii.OP_DUP},{op:Ii.OP_HASH160},{op:e.length,data:e},{op:Ii.OP_EQUALVERIFY},{op:Ii.OP_CHECKSIG}])}unlock(t,e="all",i=!1,r,s){return{sign:async(n,a)=>{let o=xi.SIGHASH_FORKID;"all"===e&&(o|=xi.SIGHASH_ALL),"none"===e&&(o|=xi.SIGHASH_NONE),"single"===e&&(o|=xi.SIGHASH_SINGLE),i&&(o|=xi.SIGHASH_ANYONECANPAY);const c=n.inputs[a],h=n.inputs.filter((t,e)=>e!==a),u=c.sourceTXID??c.sourceTransaction?.id("hex");if(null==u||void 0===u)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(""===u)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(r||=c.sourceTransaction?.outputs[c.sourceOutputIndex].satoshis,null==r||void 0===r)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(s||=c.sourceTransaction?.outputs[c.sourceOutputIndex].lockingScript,null==s)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");const d=xi.format({sourceTXID:u,sourceOutputIndex:he(c.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:r,transactionVersion:n.version,otherInputs:h,inputIndex:a,outputs:n.outputs,inputSequence:he(c.sequence,"input.sequence must have value"),subscript:s,lockTime:n.lockTime,scope:o}),l=t.sign(X(d)),f=new xi(l.r,l.s,o).toChecksigFormat(),p=t.toPublicKey().encode(!0);return new Ai([{op:f.length,data:f},{op:p.length,data:p}])},estimateLength:async()=>108}}}const Ui=t=>0===t.length||1===t.length&&0===t[0]?{op:0}:1===t.length&&t[0]>0&&t[0]<=16?{op:80+t[0]}:1===t.length&&129===t[0]?{op:79}:t.length<=75?{op:t.length,data:t}:t.length<=255?{op:76,data:t}:t.length<=65535?{op:77,data:t}:{op:78,data:t};class Di{wallet;originator;static decode(t,e="before"){let i,r;if("before"===e)i=$e.fromString(jt(he(t.chunks[0].data,"script.chunks[0].data must have value"))),r=2;else{const e=t.chunks.length-1;if(t.chunks[e].op!==Ii.OP_CHECKSIG)throw new Error("Expected OP_CHECKSIG at the end of the script");i=$e.fromString(jt(he(t.chunks[e-1].data,"public key chunk data must have value"))),r=0}const s=[];for(let e=r;e<t.chunks.length;e++){const i=t.chunks[e+1]?.op;let r=t.chunks[e].data??[];if(0===r.length&&(t.chunks[e].op>=80&&t.chunks[e].op<=95?r=[t.chunks[e].op-80]:0===t.chunks[e].op?r=[0]:79===t.chunks[e].op&&(r=[129])),s.push(r),i===Ii.OP_DROP||i===Ii.OP_2DROP)break}return{fields:s,lockingPublicKey:i}}constructor(t,e){this.wallet=t,this.originator=e}async lock(t,e,i,r,s=!1,n=!0,a="before"){const{publicKey:o}=await this.wallet.getPublicKey({protocolID:e,keyID:i,counterparty:r,forSelf:s},this.originator),c=[],h=[];if(c.push({op:o.length/2,data:Wt(o,"hex")}),c.push({op:Ii.OP_CHECKSIG}),n){const s=t.reduce((t,e)=>[...t,...e],[]),{signature:n}=await this.wallet.createSignature({data:s,protocolID:e,keyID:i,counterparty:r},this.originator);t.push(n)}for(const e of t)h.push(Ui(e));let u=t.length;for(;u>1;)h.push({op:Ii.OP_2DROP}),u-=2;return 0!==u&&h.push({op:Ii.OP_DROP}),new _i("before"===a?[...c,...h]:[...h,...c])}unlock(t,e,i,r="all",s=!1,n,a){return{sign:async(o,c)=>{let h=xi.SIGHASH_FORKID;"all"===r&&(h|=xi.SIGHASH_ALL),"none"===r&&(h|=xi.SIGHASH_NONE),"single"===r&&(h|=xi.SIGHASH_SINGLE),s&&(h|=xi.SIGHASH_ANYONECANPAY);const u=o.inputs[c],d=o.inputs.filter((t,e)=>e!==c),l=u.sourceTXID??u.sourceTransaction?.id("hex");if(null==l||void 0===l)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(n||=u.sourceTransaction?.outputs[u.sourceOutputIndex].satoshis,null==n||void 0===n)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(a||=u.sourceTransaction?.outputs[u.sourceOutputIndex].lockingScript,null==a)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");const f=xi.format({sourceTXID:l,sourceOutputIndex:he(u.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:n,transactionVersion:o.version,otherInputs:d,inputIndex:c,outputs:o.outputs,inputSequence:u.sequence??4294967295,subscript:a,lockTime:o.lockTime,scope:h}),p=X(f),{signature:g}=await this.wallet.createSignature({data:p,protocolID:t,keyID:e,counterparty:i},this.originator),y=Be.fromDER([...g]),b=new xi(y.r,y.s,h).toChecksigFormat();return new Ai([{op:b.length,data:b}])},estimateLength:async()=>73}}}class Hi{value;constructor(t){this.value=t}async computeFee(t){const e=t=>t>2**32?9:t>65536?5:t>253?3:1;let i=4;i+=e(t.inputs.length);for(let r=0;r<t.inputs.length;r++){const s=t.inputs[r];let n;if(i+=40,"object"==typeof s.unlockingScript)n=s.unlockingScript.toBinary().length;else{if("object"!=typeof s.unlockingScriptTemplate)throw new Error("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");n=await s.unlockingScriptTemplate.estimateLength(t,r)}i+=e(n),i+=n}i+=e(t.outputs.length);for(const r of t.outputs){i+=8;const t=r.lockingScript.toBinary().length;i+=e(t),i+=t}return i+=4,Math.ceil(i/1e3*this.value)}}class qi extends Hi{static ARC_POLICY_URL="https://arc.gorillapool.io/v1/policy";static instance=null;cachedRate=null;cacheTimestamp=0;cacheValidityMs;constructor(t=3e5){super(100),this.cacheValidityMs=t}static getInstance(t=3e5){return qi.instance||(qi.instance=new qi(t)),qi.instance}async fetchFeeRate(){const t=Date.now();if(null!==this.cachedRate&&t-this.cacheTimestamp<this.cacheValidityMs)return this.cachedRate;try{const e=await fetch(qi.ARC_POLICY_URL);if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const i=await e.json();if(!i.policy?.miningFee||"number"!=typeof i.policy.miningFee.satoshis||"number"!=typeof i.policy.miningFee.bytes)throw new Error("Invalid policy response format");const r=i.policy.miningFee.satoshis/i.policy.miningFee.bytes*1e3;return this.cachedRate=r,this.cacheTimestamp=t,r}catch(t){return null!==this.cachedRate?(console.warn("Failed to fetch live fee rate, using cached value:",t),this.cachedRate):(console.warn("Failed to fetch live fee rate, using default 100 sat/kb:",t),100)}}async computeFee(t){const e=await this.fetchFeeRate();return this.value=e,super.computeFee(t)}}class Vi{https;constructor(t){this.https=t}async request(t,e){return await new Promise((i,r)=>{const s=this.https.request(t,e,t=>{let e="";t.on("data",t=>{e+=t}),t.on("end",()=>{const r=t.statusCode>=200&&t.statusCode<=299,s=t.headers["content-type"],n=""!==e&&"string"==typeof s&&s.startsWith("application/json")?JSON.parse(e):e;i({status:t.statusCode,statusText:t.statusMessage,ok:r,data:n})})});s.on("error",t=>{r(t)}),null!==e.data&&void 0!==e.data&&s.write(JSON.stringify(e.data)),s.end()})}}class Ki{fetch;constructor(t){this.fetch=t}async request(t,e){const i={method:e.method,headers:e.headers,body:JSON.stringify(e.data)},r=await this.fetch(t,i),s=r.headers.get("Content-Type"),n=s?.startsWith("application/json")?await r.json():await r.text();return{ok:r.ok,status:r.status,statusText:r.statusText,data:n}}}function $i(){const t={async request(...t){throw new Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new Ki(window.fetch.bind(window));if("undefined"==typeof require)return t;try{const t=require("https");return new Vi(t)}catch(e){return t}}function ji(){return`ts-sdk-${jt(We(16))}`}class zi{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(t,e){if(this.URL=t,"string"==typeof e)this.apiKey=e,this.httpClient=$i(),this.deploymentId=ji(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const t=e??{},{apiKey:i,deploymentId:r,httpClient:s,callbackToken:n,callbackUrl:a,headers:o}=t;this.apiKey=i,this.httpClient=s??$i(),this.deploymentId=r??ji(),this.callbackToken=n,this.callbackUrl=a,this.headers=o}}requestHeaders(){const t={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(null!=this.apiKey&&""!==this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),null!=this.callbackUrl&&""!==this.callbackUrl&&(t["X-CallbackUrl"]=this.callbackUrl),null!=this.callbackToken&&""!==this.callbackToken&&(t["X-CallbackToken"]=this.callbackToken),null!=this.headers)for(const e in this.headers)t[e]=this.headers[e];return t}async broadcast(t){let e;try{e=t.toHexEF()}catch(i){if("All inputs must have source transactions when serializing to EF format"!==i.message)throw i;e=t.toHex()}const i={method:"POST",headers:this.requestHeaders(),data:{rawTx:e}};try{const t=await this.httpClient.request(`${this.URL}/v1/tx`,i);if(t.ok){const{txid:e,extraInfo:i,txStatus:r,competingTxs:s}=t.data,n=["DOUBLE_SPEND_ATTEMPTED","REJECTED","INVALID","MALFORMED","MINED_IN_STALE_BLOCK"],a=i?.toUpperCase().includes("ORPHAN")||r?.toUpperCase().includes("ORPHAN");if(n.includes(r?.toUpperCase())||a){const t={status:"error",code:r??"UNKNOWN",txid:e,description:`${r??""} ${i??""}`.trim()};return null!=s&&(t.more={competingTxs:s}),t}const o={status:"success",txid:e,message:`${r} ${i}`};return null!=s&&(o.competingTxs=s),o}{const e=typeof t.status,i={status:"error",code:"number"===e||"string"===e?t.status.toString():"ERR_UNKNOWN",description:"Unknown error"};let r=t.data;if("string"==typeof r)try{r=JSON.parse(t.data)}catch{}return"object"==typeof r&&(null!==r&&(i.more=r),null!=r&&"string"==typeof r.txid&&(i.txid=r.txid),null!=r&&"detail"in r&&"string"==typeof r.detail&&(i.description=r.detail)),i}}catch(t){return{status:"error",code:"500",description:"string"==typeof t.message?t.message:"Internal Server Error"}}}async broadcastMany(t){const e=t.map(t=>{try{return{rawTx:t.toHexEF()}}catch(e){if("All inputs must have source transactions when serializing to EF format"===e.message)return{rawTx:t.toHex()};throw e}}),i={method:"POST",headers:this.requestHeaders(),data:e};try{return(await this.httpClient.request(`${this.URL}/v1/txs`,i)).data}catch(e){const i={status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"};return t.map(()=>i)}}}class Wi{network;apiKey;URL;httpClient;constructor(t="main",e={}){const{apiKey:i,httpClient:r}=e;this.network=t,this.URL=`https://api.whatsonchain.com/v1/bsv/${t}`,this.httpClient=r??$i(),this.apiKey=i??""}async isValidRootForHeight(t,e){const i={method:"GET",headers:this.getHttpHeaders()},r=await this.httpClient.request(`${this.URL}/block/${e}/header`,i);if(r.ok){const{merkleroot:e}=r.data;return e===t}if(404===r.status)return!1;throw new Error(`Failed to verify merkleroot for height ${e} because of an error: ${JSON.stringify(r.data)} `)}async currentHeight(){try{const t={method:"GET",headers:this.getHttpHeaders()},e=await this.httpClient.request(`${this.URL}/block/headers`,t);if(e.ok)return e.data[0].height;throw new Error(`Failed to get current height because of an error: ${JSON.stringify(e.data)} `)}catch(t){throw new Error(`Failed to get current height because of an error: ${t instanceof Error?t.message:String(t)}`)}}getHttpHeaders(){const t={Accept:"application/json"};return"string"==typeof this.apiKey&&""!==this.apiKey.trim()&&(t.Authorization=this.apiKey),t}}class Gi{blockHeight;path;static fromHex(t){return Gi.fromBinary(Wt(t,"hex"))}static fromReader(t,e=!0){const i=t.readVarIntNum(),r=t.readUInt8(),s=Array(r).fill(null).map(()=>[]);let n,a,o;for(let e=0;e<r;e++){for(o=t.readVarIntNum();o>0;){a=t.readVarIntNum(),n=t.readUInt8();const i={offset:a};1&n?i.duplicate=!0:(2&n&&(i.txid=!0),i.hash=jt(t.read(32).reverse())),Array.isArray(s[e])&&0!==s[e].length||(s[e]=[]),s[e].push(i),o--}s[e].sort((t,e)=>t.offset-e.offset)}return new Gi(i,s,e)}static fromBinary(t){const e=new Ht(t);return Gi.fromReader(e)}static fromCoinbaseTxidAndHeight(t,e){return new Gi(e,[[{offset:0,hash:t,txid:!0}]])}constructor(t,e,i=!0){this.blockHeight=t,this.path=e;const r=Array(this.path.length).fill(0).map(()=>new Set);let s;this.path.forEach((t,e)=>{if(0===t.length&&0===e)throw new Error(`Empty level at height: ${e}`);const s=new Set;t.forEach(t=>{if(s.has(t.offset))throw new Error(`Duplicate offset: ${t.offset}, at height: ${e}`);if(s.add(t.offset),0===e){if(!0!==t.duplicate)for(let e=1;e<this.path.length;e++)r[e].add(t.offset>>e^1)}else if(i&&!r[e].has(t.offset))throw new Error(`Invalid offset: ${t.offset}, at height: ${e}, with legal offsets: ${Array.from(r[e]).join(", ")}`)})}),this.path[0].forEach((t,e)=>{if(0===e&&(s=this.computeRoot(t.hash)),s!==this.computeRoot(t.hash))throw new Error("Mismatched roots")})}toWriter(t){t.writeVarIntNum(this.blockHeight);const e=this.path.length;t.writeUInt8(e);for(let i=0;i<e;i++){const e=Object.keys(this.path[i]).length;t.writeVarIntNum(e);for(const e of this.path[i]){t.writeVarIntNum(e.offset);let i=0;!0===e?.duplicate&&(i|=1),void 0!==e?.txid&&null!==e.txid&&(i|=2),t.writeUInt8(i),1&i||t.write(Wt(e.hash,"hex").reverse())}}}toBinary(){const t=new se;return this.toWriter(t),t.toArray()}toBinaryUint8Array(){const t=new Dt;return this.toWriter(t),t.toUint8Array()}toHex(){return jt(this.toBinaryUint8Array())}indexOf(t){const e=this.path[0].find(e=>e.hash===t);if(null==e)throw new Error(`Transaction ID ${t} not found in the Merkle Path`);return e.offset}computeRoot(t){if("string"!=typeof t){const e=this.path[0].find(t=>Boolean(t?.hash));if(null==e)throw new Error("No valid leaf found in the Merkle Path");t=e.hash}if("string"!=typeof t)throw new Error("Transaction ID is undefined");const e=this.indexOf(t);if("number"!=typeof e)throw new Error(`This proof does not contain the txid: ${t??"undefined"}`);const i=t=>jt(Y(Wt(t,"hex").reverse()).reverse());let r=t;if(1===this.path.length&&1===this.path[0].length)return r;for(let t=0;t<this.path.length;t++){this.path[t];const s=e>>t^1,n=this.findOrComputeLeaf(t,s);if("object"!=typeof n)throw new Error(`Missing hash for index ${e} at height ${t}`);r=!0===n.duplicate?i((r??"")+(r??"")):i(s%2!=0?(n.hash??"")+(r??""):(r??"")+(n.hash??""))}return r}findOrComputeLeaf(t,e){const i=t=>jt(Y(Wt(t,"hex").reverse()).reverse());let r=this.path[t].find(t=>t.offset===e);if(null!=r)return r;if(0===t)return;const s=t-1,n=e<<1,a=this.findOrComputeLeaf(s,n);if(null==a||null==a.hash||""===a.hash)return;const o=this.findOrComputeLeaf(s,n+1);if(null==o)return;let c;return c=!0===o.duplicate?i(a.hash+a.hash):i((o.hash??"")+(a.hash??"")),r={offset:e,hash:c},r}async verify(t,e){const i=this.computeRoot(t);if(0===this.indexOf(t)){const t=await e.currentHeight();if(this.blockHeight+100<t)return!1}return await e.isValidRootForHeight(i,this.blockHeight)}combine(t){if(this.blockHeight!==t.blockHeight)throw new Error("You cannot combine paths which do not have the same block height.");if(this.computeRoot()!==t.computeRoot())throw new Error("You cannot combine paths which do not have the same root.");const e=[];for(let i=0;i<this.path.length;i++){e.push([]);for(let t=0;t<this.path[i].length;t++)e[i].push(this.path[i][t]);for(let r=0;r<t.path[i].length;r++)if(void 0===e[i].find(e=>e.offset===t.path[i][r].offset))e[i].push(t.path[i][r]);else if(void 0!==t.path[i][r]?.txid&&null!==t.path[i][r]?.txid){const s=e[i].find(e=>e.offset===t.path[i][r].offset);null!=s&&(s.txid=!0)}}this.path=e,this.trim()}trim(){const t=(t,e)=>{0!==e.length&&e.slice(-1)[0]===t||e.push(t)},e=(t,e)=>{for(let i=t.length;i>=0;i--){const r=this.path[e].findIndex(e=>e.offset===t[i]);r>=0&&this.path[e].splice(r,1)}},i=e=>{const i=[];for(const r of e)t(r>>1,i);return i};let r=[],s=[];for(let t=0;t<this.path.length;t++)this.path[t].sort((t,e)=>t.offset-e.offset);for(let e=0;e<this.path[0].length;e++){const i=this.path[0][e];if(!0===i.txid)t(i.offset>>1,r);else{const r=i.offset%2==1,n=this.path[0][e+(r?-1:1)];void 0!==n.txid&&null!==n.txid&&n.txid||t(n.offset,s)}}e(s,0);for(let t=1;t<this.path.length;t++)s=r,r=i(r),e(s,t)}}class Xi{_bumpIndex;_tx;_rawTx;_txid;inputTxids=[];isValid=void 0;get bumpIndex(){return this._bumpIndex}set bumpIndex(t){this._bumpIndex=t,this.updateInputTxids()}get hasProof(){return void 0!==this._bumpIndex}get isTxidOnly(){return void 0!==this._txid&&null!==this._txid&&null==this._rawTx&&null==this._tx}get txid(){if(void 0!==this._txid&&null!==this._txid&&""!==this._txid)return this._txid;if(null!=this._tx)return this._txid=this._tx.id("hex"),this._txid;if(null!=this._rawTx)return this._txid=jt(Y(this._rawTx)),this._txid;throw new Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=ir.fromBinary(this._rawTx),this._tx):void 0}get rawTx(){if(null!=this._rawTx)return Array.from(this._rawTx);if(null!=this._tx){const t=this._tx.toUint8Array();return this._rawTx=t,Array.from(t)}}get rawTxUint8Array(){return null!=this._rawTx?this._rawTx:null!=this._tx?(this._rawTx=this._tx.toUint8Array(),this._rawTx):void 0}constructor(t,e){if("string"==typeof t)this._txid=t;else if(t instanceof Uint8Array)this._rawTx=t;else if(Array.isArray(t))this._rawTx=new Uint8Array(t);else{if(!(t instanceof ir))throw new Error("Invalid transaction data type");this._tx=t}this.bumpIndex=e,this.updateInputTxids()}static fromTx(t,e){return new Xi(t,e)}static fromRawTx(t,e){return new Xi(t,e)}static fromTxid(t,e){return new Xi(t,e)}updateInputTxids(){if(this.hasProof||null==this.tx)this.inputTxids=[];else{const t=new Set;for(const e of this.tx.inputs)void 0!==e.sourceTXID&&null!==e.sourceTXID&&""!==e.sourceTXID&&t.add(e.sourceTXID);this.inputTxids=Array.from(t)}}toWriter(t,e){const i=e=>{t.writeUInt8(e)},r=()=>{const e=this.rawTxUint8Array;if(null==e)throw new Error("a valid serialized Transaction is expected");t.write(e)};e===Ji?this.isTxidOnly?(i(Qi.TXID_ONLY),(()=>{if(null==this._txid)throw new Error("Transaction ID (_txid) is undefined");t.writeReverse(Wt(this._txid,"hex"))})()):void 0!==this.bumpIndex?(i(Qi.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex),r()):(i(Qi.RAWTX),r()):(r(),(()=>{void 0===this.bumpIndex?i(Qi.RAWTX):(i(Qi.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex))})())}static fromReader(t,e){let i,r,s;if(e===Ji){const e=t.readUInt8();e===Qi.TXID_ONLY?s=Xi.fromTxid(jt(t.readReverse(32))):(e===Qi.RAWTX_AND_BUMP_INDEX&&(r=t.readVarIntNum()),i=ir.fromReader(t),s=Xi.fromTx(i,r))}else i=ir.fromReader(t),r=0!==t.readUInt8()?t.readVarIntNum():void 0,s=Xi.fromTx(i,r);return s}}const Yi=4022206465,Ji=4022206466,Zi=16843009;var Qi;!function(t){t[t.RAWTX=0]="RAWTX",t[t.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",t[t.TXID_ONLY=2]="TXID_ONLY"}(Qi||(Qi={}));class tr{bumps=[];txs=[];version=Ji;atomicTxid=void 0;txidIndex=void 0;rawBytesCache;hexCache;needsSort=!0;constructor(t=Ji){this.version=t}invalidateSerializationCaches(){this.rawBytesCache=void 0,this.hexCache=void 0}markMutated(t=!0){this.invalidateSerializationCaches(),t&&(this.needsSort=!0)}ensureSerializableState(){for(const t of this.txs)t.txid}ensureSortedForSerialization(){this.needsSort&&this.sortTxs()}getSerializedBytes(){if(this.ensureSerializableState(),null==this.rawBytesCache){this.ensureSortedForSerialization();const t=new Dt;this.toWriter(t),this.rawBytesCache=t.toUint8Array()}return this.rawBytesCache}getBeefForAtomic(t){this.needsSort&&this.sortTxs();const e=this.findTxid(t);if(null==e)throw new Error(`${t} does not exist in this Beef`);const i=this.txs[this.txs.length-1]===e?this:this.clone();if(i!==this){const e=this.txs.findIndex(e=>e.txid===t);i.txs.splice(e+1)}const r=new Dt;return r.writeUInt32LE(Zi),r.writeReverse(Wt(t,"hex")),{beef:i,writer:r}}findTxid(t){return this.ensureTxidIndex().get(t)}ensureTxidIndex(){if(null==this.txidIndex){this.txidIndex=new Map;for(const t of this.txs)this.txidIndex.set(t.txid,t)}return this.txidIndex}deleteFromIndex(t){this.txidIndex?.delete(t)}addToIndex(t){this.txidIndex?.set(t.txid,t)}makeTxidOnly(t){const e=this.txs.findIndex(e=>e.txid===t);if(-1===e)return;let i=this.txs[e];return i.isTxidOnly||(this.deleteFromIndex(t),this.txs.splice(e,1),this.markMutated(!0),i=this.mergeTxidOnly(t)),i}findBump(t){return this.bumps.find(e=>e.path[0].some(e=>e.hash===t))}findTransactionForSigning(t){const e=this.findTxid(t);if(null!=e&&null!=e.tx){for(const t of e.tx.inputs)if(null==t.sourceTransaction){const e=this.findTxid(he(t.sourceTXID,"sourceTXID must be valid"));null!=e&&(t.sourceTransaction=e.tx)}return e.tx}}findAtomicTransaction(t){const e=this.findTxid(t);if(null==e||null==e.tx)return;const i=(t,e)=>{const r=t.findBump(e.id("hex"));if(null!=r)e.merklePath=r;else for(const r of e.inputs){if(null==r.sourceTransaction){const e=t.findTxid(he(r.sourceTXID,"sourceTXID must be valid"));null!=e&&(r.sourceTransaction=e.tx)}if(null!=r.sourceTransaction){const e=t.findBump(r.sourceTransaction.id("hex"));null!=e?r.sourceTransaction.merklePath=e:i(t,r.sourceTransaction)}}};return i(this,e.tx),e.tx}mergeBump(t){let e;this.markMutated(!1);for(let i=0;i<this.bumps.length;i++){const r=this.bumps[i];if(r===t)return i;if(r.blockHeight===t.blockHeight&&r.computeRoot()===t.computeRoot()){r.combine(t),e=i;break}}void 0===e&&(e=this.bumps.length,this.bumps.push(t));const i=this.bumps[e];for(const t of this.txs){const r=t.txid;if(null==t.bumpIndex)for(const s of i.path[0])if(s.hash===r){t.bumpIndex=e,s.txid=!0;break}}return e}mergeRawTx(t,e){this.markMutated(!0);const i=new Xi(t,e);return this.removeExistingTxid(i.txid),this.txs.push(i),this.addToIndex(i),this.tryToValidateBumpIndex(i),i}mergeTransaction(t){this.markMutated(!0);const e=t.id("hex");let i;this.removeExistingTxid(e),null!=t.merklePath&&(i=this.mergeBump(t.merklePath));const r=new Xi(t,i);if(this.txs.push(r),this.addToIndex(r),this.tryToValidateBumpIndex(r),i=r.bumpIndex,void 0===i)for(const e of t.inputs)null!=e.sourceTransaction&&this.mergeTransaction(e.sourceTransaction);return r}removeExistingTxid(t){const e=this.txs.findIndex(e=>e.txid===t);e>=0&&(this.deleteFromIndex(t),this.txs.splice(e,1),this.markMutated(!0))}mergeTxidOnly(t){let e=this.findTxid(t);return null==e&&(e=new Xi(t),this.txs.push(e),this.addToIndex(e),this.tryToValidateBumpIndex(e),this.markMutated(!0)),e}mergeBeefTx(t){let e=this.findTxid(t.txid);if(t.isTxidOnly&&null==e?e=this.mergeTxidOnly(t.txid):null==t._tx||null!=e&&!e.isTxidOnly?null==t._rawTx||null!=e&&!e.isTxidOnly||(e=this.mergeRawTx(t._rawTx)):e=this.mergeTransaction(t._tx),null==e)throw new Error(`Failed to merge BeefTx for txid: ${t.txid}`);return e}mergeBeef(t){const e=t instanceof tr?t:tr.fromBinary(t);for(const t of e.bumps)this.mergeBump(t);for(const t of e.txs)this.mergeBeefTx(t)}isValid(t){return this.verifyValid(t).valid}async verify(t,e){const i=this.verifyValid(e);if(!i.valid)return!1;for(const e of Object.keys(i.roots))if(!await t.isValidRootForHeight(i.roots[e],Number(e)))return!1;return!0}verifyValid(t){const e={valid:!1,roots:{}},i=this.sortTxs();if(i.missingInputs.length>0||i.notValid.length>0||i.txidOnly.length>0&&!0!==t||i.withMissingInputs.length>0)return e;const r={};for(const i of this.txs)if(i.isTxidOnly){if(!0!==t)return e;r[i.txid]=!0}const s=(t,i)=>{const r=t.computeRoot(i);return void 0!==e.roots[t.blockHeight]&&""!==e.roots[t.blockHeight]||(e.roots[t.blockHeight]=r),e.roots[t.blockHeight]===r};for(const t of this.bumps)for(const i of t.path[0])if(!0===i.txid&&"string"==typeof i.hash&&i.hash.length>0&&(r[i.hash]=!0,!s(t,i.hash)))return e;for(const t of this.txs)if(void 0!==t.bumpIndex&&null==this.bumps[t.bumpIndex].path[0].find(e=>e.hash===t.txid))return e;for(const t of this.txs){for(const i of t.inputTxids)if(!r[i])return e;r[t.txid]=!0}return e.valid=!0,e}toWriter(t){t.writeUInt32LE(this.version),t.writeVarIntNum(this.bumps.length);for(const e of this.bumps)t.write(e.toBinary());t.writeVarIntNum(this.txs.length);for(const e of this.txs)e.toWriter(t,this.version)}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}toBinaryAtomic(t){const{beef:e,writer:i}=this.getBeefForAtomic(t);return e.toWriter(i),i.toArray()}toUint8ArrayAtomic(t){const{beef:e,writer:i}=this.getBeefForAtomic(t),r=e.getSerializedBytes(),s=i.toUint8Array(),n=new Uint8Array(s.length+r.length);return n.set(s,0),n.set(r,s.length),n}toHex(){if(null!=this.hexCache)return this.hexCache;const t=this.getSerializedBytes(),e=jt(t);return this.hexCache=e,e}static fromReader(t){let e,i=t.readUInt32LE();if(i===Zi&&(e=jt(t.readReverse(32)),i=t.readUInt32LE()),i!==Yi&&i!==Ji)throw new Error(`Serialized BEEF must start with 4022206465 or ${Ji} but starts with ${i}`);const r=new tr(i),s=t.readVarIntNum();for(let e=0;e<s;e++){const e=Gi.fromReader(t,!1);r.bumps.push(e)}const n=t.readVarIntNum();for(let e=0;e<n;e++){const e=Xi.fromReader(t,i);r.txs.push(e)}return r.atomicTxid=e,r}static fromBinary(t){const e=Ht.makeReader(t);return tr.fromReader(e)}static fromString(t,e="hex"){const i=zt(t,e),r=new Ht(i);return tr.fromReader(r)}tryToValidateBumpIndex(t){if(void 0!==t.bumpIndex)return!0;const e=t.txid;for(let i=0;i<this.bumps.length;i++){const r=this.bumps[i].path[0].findIndex(t=>t.hash===e);if(r>=0)return t.bumpIndex=i,this.bumps[i].path[0][r].txid=!0,!0}return!1}sortTxs(){const t={},e={};let i=[];const r=[],s=[];for(const n of this.txs)e[n.txid]=n,n.isValid=n.hasProof,n.isValid?(t[n.txid]=!0,r.push(n)):n.isTxidOnly&&0===n.inputTxids.length?(t[n.txid]=!0,s.push(n)):i.push(n);const n={},a=[],o=i;i=[];for(const t of o){let r=!1;for(const i of t.inputTxids)void 0===e[i]&&(n[i]=!0,r=!0);r?a.push(t):i.push(t)}for(;i.length>0;){const e=i;i=[];for(const s of e)s.inputTxids.every(e=>t[e])?(t[s.txid]=!0,r.push(s)):i.push(s);if(e.length===i.length)break}const c=i;return this.txs=a.concat(c).concat(s).concat(r),this.needsSort=!1,this.invalidateSerializationCaches(),{missingInputs:Object.keys(n),notValid:c.map(t=>t.txid),valid:Object.keys(t),withMissingInputs:a.map(t=>t.txid),txidOnly:s.map(t=>t.txid)}}clone(){const t=new tr;return t.version=this.version,t.bumps=Array.from(this.bumps),t.txs=Array.from(this.txs),t.txidIndex=void 0,t.needsSort=this.needsSort,t.hexCache=this.hexCache,t.rawBytesCache=this.rawBytesCache,t}trimKnownTxids(t){let e=!1;for(let i=0;i<this.txs.length;){const r=this.txs[i];r.isTxidOnly&&t.includes(r.txid)?(this.deleteFromIndex(r.txid),this.txs.splice(i,1),e=!0):i++}const i=new Set;for(const t of this.txs)void 0!==t.bumpIndex&&i.add(t.bumpIndex);if(i.size<this.bumps.length){const t=new Map;let r=0;for(let e=0;e<this.bumps.length;e++)i.has(e)&&(t.set(e,r),r++);this.bumps=this.bumps.filter((t,e)=>i.has(e));for(const e of this.txs)if(void 0!==e.bumpIndex){const i=t.get(e.bumpIndex);if(void 0===i)throw new Error(`Internal error: bumpIndex ${e.bumpIndex} not found in indexMap`);e.bumpIndex=i}e=!0}e&&this.markMutated(!0)}getValidTxids(){return this.sortTxs().valid}toLogString(){let t="";t+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}\n`;let e=-1;for(const i of this.bumps)e++,t+=` BUMP ${e}\n block: ${i.blockHeight}\n txids: [\n${i.path[0].filter(t=>!0===t.txid).map(t=>` '${t.hash??""}'`).join(",\n")}\n ]\n`;e=-1;for(const i of this.txs)e++,t+=` TX ${e}\n txid: ${i.txid}\n`,void 0!==i.bumpIndex&&(t+=` bumpIndex: ${i.bumpIndex}\n`),i.isTxidOnly?t+=" txidOnly\n":t+=` rawTx length=${i.rawTx?.length??0}\n`,i.inputTxids.length>0&&(t+=` inputs: [\n${i.inputTxids.map(t=>` '${t}'`).join(",\n")}\n ]\n`);return t}addComputedLeaves(){const t=t=>jt(Y(Wt(t,"hex").reverse()).reverse());for(const e of this.bumps)for(let i=1;i<e.path.length;i++)for(const r of e.path[i-1])if("string"==typeof r.hash&&!(1&r.offset)){const s=e.path[i-1].find(t=>t.offset===r.offset+1),n=r.offset>>1;void 0!==s&&"string"==typeof s.hash&&e.path[i].every(t=>t.offset!==n)&&e.path[i].push({offset:n,hash:t(s.hash+r.hash)})}}}const er=tr;class ir{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;rawBytesCache;hexCache;static addPathOrInputs(t,e,i){if("number"==typeof t.pathIndex){const e=i[t.pathIndex];if("object"!=typeof e)throw new Error("Invalid merkle path index found in BEEF!");t.tx.merklePath=e}else for(const r of t.tx.inputs){if(void 0===r.sourceTXID)throw new Error("Input sourceTXID is undefined");const t=e[r.sourceTXID];if("object"!=typeof t)throw new Error(`Reference to unknown TXID in BEEF: ${r.sourceTXID??"undefined"}`);r.sourceTransaction=t.tx,this.addPathOrInputs(t,e,i)}}static fromBEEF(t,e){const{tx:i}=ir.fromAnyBeef(t,e);return i}static fromAtomicBEEF(t){const{tx:e,txid:i,beef:r}=ir.fromAnyBeef(t);if(i!==r.atomicTxid)throw null!=r.atomicTxid?new Error(`Transaction with TXID ${r.atomicTxid} not found in BEEF data.`):new Error("beef must conform to BRC-95 and must contain the subject txid.");return e}static fromAnyBeef(t,e){const i=tr.fromBinary(t);if(i.txs.length<1)throw new Error("beef must include at least one transaction.");const r=e??i.atomicTxid??i.txs.slice(-1)[0].txid,s=i.findAtomicTransaction(r);if(null==s)throw null!=e?new Error(`Transaction with TXID ${r} not found in BEEF data.`):new Error("beef does not contain transaction for atomic txid.");return{tx:s,beef:i,txid:r}}static fromEF(t){const e=Ht.makeReader(t),i=e.readUInt32LE();if("0000000000ef"!==jt(e.read(6)))throw new Error("Invalid EF marker");const r=e.readVarIntNum(),s=[];for(let t=0;t<r;t++){const t=jt(e.readReverse(32)),i=e.readUInt32LE(),r=e.readVarIntNum(),n=e.read(r),a=Ai.fromBinary(n),o=e.readUInt32LE(),c=e.readUInt64LEBn().toNumber(),h=e.readVarIntNum(),u=e.read(h),d=_i.fromBinary(u),l=new ir(void 0,[],[],void 0);l.outputs=Array(i+1).fill(null),l.outputs[i]={satoshis:c,lockingScript:d},s.push({sourceTransaction:l,sourceTXID:t,sourceOutputIndex:i,unlockingScript:a,sequence:o})}const n=e.readVarIntNum(),a=[];for(let t=0;t<n;t++){const t=e.readUInt64LEBn().toNumber(),i=e.readVarIntNum(),r=e.read(i),s=_i.fromBinary(r);a.push({satoshis:t,lockingScript:s})}const o=e.readUInt32LE();return new ir(i,s,a,o)}static parseScriptOffsets(t){const e=Ht.makeReader(t),i=[],r=[];e.pos+=4;const s=e.readVarIntNum();for(let t=0;t<s;t++){e.pos+=36;const r=e.readVarIntNum();i.push({vin:t,offset:e.pos,length:r}),e.pos+=r+4}const n=e.readVarIntNum();for(let t=0;t<n;t++){e.pos+=8;const i=e.readVarIntNum();r.push({vout:t,offset:e.pos,length:i}),e.pos+=i}return{inputs:i,outputs:r}}static fromReader(t){const e=t.readUInt32LE(),i=t.readVarIntNum(),r=[];for(let e=0;e<i;e++){const e=jt(t.readReverse(32)),i=t.readUInt32LE(),s=t.readVarIntNum(),n=t.read(s),a=Ai.fromBinary(n),o=t.readUInt32LE();r.push({sourceTXID:e,sourceOutputIndex:i,unlockingScript:a,sequence:o})}const s=t.readVarIntNum(),n=[];for(let e=0;e<s;e++){const e=t.readUInt64LEBn().toNumber(),i=t.readVarIntNum(),r=t.read(i),s=_i.fromBinary(r);n.push({satoshis:e,lockingScript:s})}const a=t.readUInt32LE();return new ir(e,r,n,a)}static fromBinary(t){const e=t.slice(),i=Uint8Array.from(e),r=new Ht(i),s=ir.fromReader(r);return s.rawBytesCache=i,s}static fromHex(t){const e=zt(t,"hex"),i=new Ht(e),r=ir.fromReader(i);return r.rawBytesCache=e,r.hexCache=jt(e),r}static fromHexEF(t){return ir.fromEF(zt(t,"hex"))}static fromHexBEEF(t,e){return ir.fromBEEF(Wt(t,"hex"),e)}constructor(t=1,e=[],i=[],r=0,s=new Map,n){this.version=t,this.inputs=e,this.outputs=i,this.lockTime=r,this.metadata=s,this.merklePath=n}invalidateSerializationCaches(){this.cachedHash=void 0,this.rawBytesCache=void 0,this.hexCache=void 0}addInput(t){if(void 0===t.sourceTXID&&void 0===t.sourceTransaction)throw new Error("A reference to an an input transaction is required. If the input transaction itself cannot be referenced, its TXID must still be provided.");void 0===t.sequence&&(t.sequence=4294967295),this.invalidateSerializationCaches(),this.inputs.push(t)}addOutput(t){if(this.cachedHash=void 0,!0!==t.change){if(void 0===t.satoshis)throw new Error("either satoshis must be defined or change must be set to true");if(t.satoshis<0)throw new Error("satoshis must be a positive integer or zero")}if(null==t.lockingScript)throw new Error("lockingScript must be defined");this.outputs.push(t)}addP2PKHOutput(t,e){const i=(new Fi).lock(t);if(void 0===e)return this.addOutput({lockingScript:i,change:!0});this.addOutput({lockingScript:i,satoshis:e})}updateMetadata(t){this.metadata={...this.metadata,...t}}async fee(t=qi.getInstance(),e="equal"){if(this.invalidateSerializationCaches(),"number"==typeof t){const e=t;t={computeFee:async()=>e}}const i=await t.computeFee(this),r=this.calculateChange(i);r<=0?this.outputs=this.outputs.filter(t=>!0!==t.change):this.distributeChange(r,e)}calculateChange(t){let e=0;for(const t of this.inputs){if("object"!=typeof t.sourceTransaction)throw new Error("Source transactions are required for all inputs during fee computation");e+=t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0}e-=t;for(const t of this.outputs)!0!==t.change&&void 0!==t.satoshis&&(e-=t.satoshis);return e}distributeChange(t,e){let i=0;const r=this.outputs.filter(t=>t.change);if("random"===e?i=this.distributeRandomChange(t,r):"equal"===e&&(i=this.distributeEqualChange(t,r)),i<t){const e=this.outputs[this.outputs.length-1];void 0!==e.satoshis?e.satoshis+=t-i:e.satoshis=t-i}}distributeRandomChange(t,e){let i=0,r=t;const s=Array(e.length).fill(1);r-=e.length,i+=e.length;for(let t=0;t<e.length-1;t++){const e=this.benfordNumber(0,r);s[t]=s[t]+e,i+=e,r-=e}for(const t of this.outputs)!0===t.change&&(t.satoshis=s.shift());return i}distributeEqualChange(t,e){let i=0;const r=Math.floor(t/e.length);for(const t of e)i+=r,t.satoshis=r;return i}benfordNumber(t,e){const i=Math.floor(9*Math.random())+1;return Math.floor(t+(e-t)*Math.log10(1+1/i)/Math.log10(10))}getFee(){let t=0;for(const e of this.inputs){if("object"!=typeof e.sourceTransaction)throw new Error("Source transactions or sourceSatoshis are required for all inputs to calculate fee");t+=e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0}let e=0;for(const t of this.outputs)e+=t.satoshis??0;return t-e}async sign(){this.invalidateSerializationCaches();for(const t of this.outputs)if(void 0===t.satoshis)throw!0===t.change?new Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing."):new Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");const t=await Promise.all(this.inputs.map(async(t,e)=>"object"==typeof this.inputs[e].unlockingScriptTemplate?await(this.inputs[e]?.unlockingScriptTemplate?.sign(this,e)):await Promise.resolve(void 0)));for(let e=0,i=this.inputs.length;e<i;e++)"object"==typeof this.inputs[e].unlockingScriptTemplate&&(this.inputs[e].unlockingScript=t[e])}async broadcast(t=function(t=!1,e={}){return new zi(t?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",e)}()){return await t.broadcast(this)}writeTransactionBody(t){t.writeUInt32LE(this.version),t.writeVarIntNum(this.inputs.length);for(const e of this.inputs){if(void 0===e.sourceTXID){if(null==e.sourceTransaction)throw new Error("sourceTransaction is undefined");t.write(e.sourceTransaction.hash())}else t.writeReverse(Wt(e.sourceTXID,"hex"));if(t.writeUInt32LE(e.sourceOutputIndex),null==e.unlockingScript)throw new Error("unlockingScript is undefined");const i=e.unlockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i),t.writeUInt32LE(e.sequence??4294967295)}t.writeVarIntNum(this.outputs.length);for(const e of this.outputs){t.writeUInt64LE(e.satoshis??0);const i=e.lockingScript.toUint8Array();t.writeVarIntNum(i.length),t.write(i)}t.writeUInt32LE(this.lockTime)}buildSerializedBytes(){const t=new Dt;return this.writeTransactionBody(t),t.toUint8Array()}getSerializedBytes(){return null==this.rawBytesCache&&(this.rawBytesCache=this.buildSerializedBytes()),this.rawBytesCache}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}writeEF(t){t.writeUInt32LE(this.version),t.write([0,0,0,0,0,239]),t.writeVarIntNum(this.inputs.length);for(const e of this.inputs){if(void 0===e.sourceTransaction)throw new Error("All inputs must have source transactions when serializing to EF format");if(void 0===e.sourceTXID?t.write(e.sourceTransaction.hash()):t.write(Wt(e.sourceTXID,"hex").reverse()),t.writeUInt32LE(e.sourceOutputIndex),null==e.unlockingScript)throw new Error("unlockingScript is undefined");const i=e.unlockingScript.toBinary();t.writeVarIntNum(i.length),t.write(i),t.writeUInt32LE(e.sequence??4294967295),t.writeUInt64LE(e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0);const r=e.sourceTransaction.outputs[e.sourceOutputIndex].lockingScript.toBinary();t.writeVarIntNum(r.length),t.write(r)}t.writeVarIntNum(this.outputs.length);for(const e of this.outputs){t.writeUInt64LE(e.satoshis??0);const i=e.lockingScript.toBinary();t.writeVarIntNum(i.length),t.write(i)}t.writeUInt32LE(this.lockTime)}toEF(){const t=new se;return this.writeEF(t),t.toArray()}toEFUint8Array(){const t=new Dt;return this.writeEF(t),t.toUint8Array()}toHexEF(){return jt(this.toEFUint8Array())}toHex(){if(null!=this.hexCache)return this.hexCache;const t=this.getSerializedBytes(),e=jt(t);return this.hexCache=e,e}toHexBEEF(){return jt(this.toBEEF())}toHexAtomicBEEF(){return jt(this.toAtomicBEEF())}hash(t){return null==this.cachedHash&&(this.cachedHash=Y(this.getSerializedBytes())),"hex"===t?jt(this.cachedHash):this.cachedHash}id(t){const e=[...this.hash()];return e.reverse(),"hex"===t?jt(e):e}async verify(t=function(){return new Wi}(),e,i){const r=new Set,s=[this];for(;s.length>0;){const n=s.shift(),a=n?.id("hex")??"";if(null!=a&&""!==a&&r.has(a))continue;if("object"==typeof n?.merklePath){if("scripts only"===t){null!=a&&r.add(a);continue}if(await n.merklePath.verify(a,t)){r.add(a);continue}throw new Error(`Invalid merkle path for transaction ${a}`)}if(void 0!==e){if(void 0===n)throw new Error("Transaction is undefined");const t=ir.fromEF(n.toEF());if(delete t.outputs[0].satoshis,t.outputs[0].change=!0,await t.fee(e),n.getFee()<t.getFee())throw new Error(`Verification failed because the transaction ${a} has an insufficient fee and has not been mined.`)}let o=0;if(void 0===n)throw new Error("Transaction is undefined");for(let t=0;t<n.inputs.length;t++){const e=n.inputs[t];if("object"!=typeof e.sourceTransaction)throw new Error(`Verification failed because the input at index ${t} of transaction ${a} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if("object"!=typeof e.unlockingScript)throw new Error(`Verification failed because the input at index ${t} of transaction ${a} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);const c=e.sourceTransaction.outputs[e.sourceOutputIndex];o+=c.satoshis??0;const h=e.sourceTransaction.id("hex");r.has(h)||s.push(e.sourceTransaction);const u=n.inputs.filter((e,i)=>i!==t);if(void 0===e.sourceTXID&&(e.sourceTXID=h),!new Mi({sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:n.version,otherInputs:u,unlockingScript:e.unlockingScript,inputSequence:e.sequence??4294967295,inputIndex:t,outputs:n.outputs,lockTime:n.lockTime,memoryLimit:i}).validate())return!1}let c=0;for(const t of n.outputs){if("number"!=typeof t.satoshis)throw new Error("Every output must have a defined amount during transaction verification.");c+=t.satoshis}if(c>o)return!1;r.add(a)}return!0}writeSerializedBEEF(t,e){t.writeUInt32LE(Yi);const i=[],r=new Map,s=new Map,n=[],a=new Set,o=t=>{const c=t.id("hex");if(a.has(c))return;const h={tx:t},u=t.merklePath,d="object"==typeof u;if(d&&null!=u&&(h.pathIndex=(t=>{const e=r.get(t);if(void 0!==e)return e;const n=`${t.blockHeight}:${t.computeRoot()}`,a=s.get(n);if(void 0!==a)return i[a].combine(t),r.set(t,a),a;const o=i.length;return i.push(t),r.set(t,o),s.set(n,o),o})(u)),!d)for(let i=t.inputs.length-1;i>=0;i--){const r=t.inputs[i];if("object"==typeof r.sourceTransaction)o(r.sourceTransaction);else if(!1===e)throw new Error("A required source transaction is missing!")}a.add(c),n.push(h)};o(this),t.writeVarIntNum(i.length);for(const e of i)t.write(e.toBinary());t.writeVarIntNum(n.length);for(const e of n)t.write(e.tx.toBinary()),"number"==typeof e.pathIndex?(t.writeUInt8(1),t.writeVarIntNum(e.pathIndex)):t.writeUInt8(0);return t.toArray()}toBEEF(t){const e=new se;return this.writeSerializedBEEF(e,t),e.toArray()}toBEEFUint8Array(t){const e=new Dt;return this.writeSerializedBEEF(e,t),e.toArray()}toAtomicBEEF(t){const e=this.hash(),i=this.toBEEF(t);return[1,1,1,1].concat(e,i)}toAtomicBEEFUint8Array(t){const e=new Dt;e.write([1,1,1,1]);const i=this.hash();return e.write(i),this.writeSerializedBEEF(e,t),e.toUint8Array()}async completeWithWallet(t,e,i,r){const s=this.inputs.length,n=this.outputs.length,a={description:e??`Transaction with ${s} input(s) and ${n} output(s)`,inputs:[],outputs:[],lockTime:this.lockTime,version:this.version},o=this.inputs.some(t=>null!=t.unlockingScriptTemplate),c=new tr;for(let t=0;t<this.inputs.length;t++){const e=this.inputs[t];if(null==e.sourceTransaction)throw new Error("All inputs must have a sourceTransaction when using completeWithWallet");const i=e.sourceTransaction.toBEEF();c.mergeBeef(i);const r={outpoint:`${e.sourceTransaction.id("hex")}.${e.sourceOutputIndex}`,inputDescription:"Input from source transaction",sequenceNumber:e.sequence};if(o)if(null!=e.unlockingScriptTemplate){const i=await e.unlockingScriptTemplate.estimateLength(this,t);r.unlockingScriptLength=i}else{if(null==e.unlockingScript)throw new Error(`Input ${t} must have either an unlockingScript or unlockingScriptTemplate`);r.unlockingScript=e.unlockingScript.toHex()}else{if(null==e.unlockingScript)throw new Error("All inputs must have an unlockingScript when using completeWithWallet");r.unlockingScript=e.unlockingScript.toHex()}a.inputs.push(r)}this.inputs.length>0&&(a.inputBEEF=c.toBinary());for(const t of this.outputs)a.outputs.push({satoshis:t.satoshis,lockingScript:t.lockingScript.toHex(),outputDescription:"Output from source transaction"});let h;if(null!=this.metadata?.labels&&Array.isArray(this.metadata.labels)&&(a.labels=this.metadata.labels),o){a.options={...r,signAndProcess:!1};const{signableTransaction:e}=await t.createAction(a,i);if(null==e)throw new Error("Wallet createAction did not return signableTransaction");const s=ir.fromBEEF(e.tx),n={};for(let t=0;t<this.inputs.length;t++){const e=this.inputs[t];if(null!=e.unlockingScriptTemplate){const i=await e.unlockingScriptTemplate.sign(s,t);n[t]={unlockingScript:i.toHex()}}else null!=e.unlockingScript&&(n[t]={unlockingScript:e.unlockingScript.toHex()})}const o=null!=r?{acceptDelayedBroadcast:r.acceptDelayedBroadcast,returnTXIDOnly:r.returnTXIDOnly,noSend:r.noSend,sendWith:r.sendWith}:void 0,c=await t.signAction({reference:e.reference,spends:n,options:o},i);if(null==c.tx)throw new Error("Wallet signAction did not return transaction data");h=c.tx}else{null!=r&&(a.options=r);const{tx:e}=await t.createAction(a,i);if(null==e)throw new Error("Wallet createAction did not return transaction data");h=e}const u=ir.fromAtomicBEEF(h);this.version=u.version,this.inputs=u.inputs,this.outputs=u.outputs,this.lockTime=u.lockTime,this.merklePath=u.merklePath,this.cachedHash=u.cachedHash,this.metadata={...this.metadata,...u.metadata}}}var rr;new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),function(t){t[t.Silent=0]="Silent",t[t.App=1]="App",t[t.Counterparty=2]="Counterparty"}(rr||(rr={}));class sr{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(t,e,i){this.cacheSharedSecret=e,this.retrieveCachedSharedSecret=i,this.anyone=new Je(1).toPublicKey(),this.rootKey="anyone"===t?new Je(1):t,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(t,e,i,r=!1){return i=this.normalizeCounterparty(i),r?this.rootKey.deriveChild(i,this.computeInvoiceNumber(t,e),this.cacheSharedSecret,this.retrieveCachedSharedSecret).toPublicKey():i.deriveChild(this.rootKey,this.computeInvoiceNumber(t,e),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}derivePrivateKey(t,e,i){return i=this.normalizeCounterparty(i),this.rootKey.deriveChild(i,this.computeInvoiceNumber(t,e),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}deriveSymmetricKey(t,e,i){i="anyone"===i?this.anyone:this.normalizeCounterparty(i);const r=this.derivePublicKey(t,e,i),s=this.derivePrivateKey(t,e,i);return new wi(s.deriveSharedSecret(r)?.x?.toArray()??[])}revealCounterpartySecret(t){if("self"===t)throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");t=this.normalizeCounterparty(t);const e=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(e,"test").toHex()===this.rootKey.deriveChild(t,"test").toHex())throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(t).encode(!0)}revealSpecificSecret(t,e,i){t=this.normalizeCounterparty(t);const r=this.rootKey.deriveSharedSecret(t),s=Wt(this.computeInvoiceNumber(e,i),"utf8");return Z(r.encode(!0),s)}normalizeCounterparty(t){if(null==t)throw new Error("counterparty must be self, anyone or a public key!");return"self"===t?this.rootKey.toPublicKey():"anyone"===t?new Je(1).toPublicKey():"string"==typeof t?$e.fromString(t):t}computeInvoiceNumber(t,e){const i=t[0];if(!Number.isInteger(i)||i<0||i>2)throw new Error("Protocol security level must be 0, 1, or 2");const r=t[1].toLowerCase().trim();if(e.length>800)throw new Error("Key IDs must be 800 characters or less");if(e.length<1)throw new Error("Key IDs must be 1 character or more");if(r.length>400){if(!r.startsWith("specific linkage revelation "))throw new Error("Protocol names must be 400 characters or less");if(r.length>430)throw new Error("Specific linkage revelation protocol names must be 430 characters or less")}if(r.length<5)throw new Error("Protocol names must be 5 characters or more");if(r.includes(" "))throw new Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(r))throw new Error("Protocol names can only contain letters, numbers and spaces");if(r.endsWith(" protocol"))throw new Error('No need to end your protocol name with " protocol"');return`${i}-${r}-${e}`}}class nr{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(t,e){this.rootKey="anyone"===t?new Je(1):t,this.keyDeriver=new sr(this.rootKey,(t,e,i)=>{this.cacheSet(`${t.toString()}-${e.toString()}`,i)},(t,e)=>this.cacheGet(`${t.toString()}-${e.toString()}`)),this.identityKey=this.rootKey.toPublicKey().toString(),this.cache=new Map;const i=e?.maxCacheSize;this.maxCacheSize=null!=i&&!isNaN(i)&&i>0?i:1e3}derivePublicKey(t,e,i,r=!1){const s=this.generateCacheKey("derivePublicKey",t,e,i,r);if(this.cache.has(s)){const t=this.cacheGet(s);if(void 0===t)throw new Error("Cached value is undefined");return t}{const n=this.keyDeriver.derivePublicKey(t,e,i,r);return this.cacheSet(s,n),n}}derivePrivateKey(t,e,i){const r=this.generateCacheKey("derivePrivateKey",t,e,i);if(this.cache.has(r)){const t=this.cacheGet(r);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.derivePrivateKey(t,e,i);return this.cacheSet(r,s),s}}deriveSymmetricKey(t,e,i){const r=this.generateCacheKey("deriveSymmetricKey",t,e,i);if(this.cache.has(r)){const t=this.cacheGet(r);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.deriveSymmetricKey(t,e,i);return this.cacheSet(r,s),s}}revealCounterpartySecret(t){const e=this.generateCacheKey("revealCounterpartySecret",t);if(this.cache.has(e)){const t=this.cacheGet(e);if(void 0===t)throw new Error("Cached value is undefined");return t}{const i=this.keyDeriver.revealCounterpartySecret(t);return this.cacheSet(e,i),i}}revealSpecificSecret(t,e,i){const r=this.generateCacheKey("revealSpecificSecret",t,e,i);if(this.cache.has(r)){const t=this.cacheGet(r);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.revealSpecificSecret(t,e,i);return this.cacheSet(r,s),s}}generateCacheKey(t,...e){return`${t}|${e.map(t=>this.serializeArgument(t)).join("|")}`}serializeArgument(t){return t instanceof $e||t instanceof Je?t.toString():Array.isArray(t)?t.map(t=>this.serializeArgument(t)).join(","):"object"==typeof t&&null!==t?JSON.stringify(t):String(t)}cacheGet(t){const e=this.cache.get(t);return this.cache.delete(t),void 0!==e&&this.cache.set(t,e),e}cacheSet(t,e){if(this.cache.size>=this.maxCacheSize){const t=this.cache.keys().next().value;this.cache.delete(t)}this.cache.set(t,e)}}const ar=class{keyDeriver;constructor(t){"string"!=typeof t.identityKey&&(t=new nr(t)),this.keyDeriver=t}async getPublicKey(t){if(t.identityKey){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==t.protocolID||null==t.keyID||""===t.keyID)throw new Error("protocolID and keyID are required if identityKey is false or undefined.");return{publicKey:(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePublicKey(t.protocolID,t.keyID,t.counterparty??"self",t.forSelf).toString()}}async revealCounterpartyKeyLinkage(t){const{publicKey:e}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const i=this.keyDeriver.revealCounterpartySecret(t.counterparty),r=(new Pi).generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),$e.fromString(t.counterparty),Te.fromDER(i)),s=[...r.R.encode(!0),...r.SPrime.encode(!0),...r.z.toArray()],n=(new Date).toISOString(),{ciphertext:a}=await this.encrypt({plaintext:i,protocolID:[2,"counterparty linkage revelation"],keyID:n,counterparty:t.verifier}),{ciphertext:o}=await this.encrypt({plaintext:s,protocolID:[2,"counterparty linkage revelation"],keyID:n,counterparty:t.verifier});return{prover:e,verifier:t.verifier,counterparty:t.counterparty,revelationTime:n,encryptedLinkage:a,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(t){const{publicKey:e}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const i=this.keyDeriver.revealSpecificSecret(t.counterparty,t.protocolID,t.keyID),{ciphertext:r}=await this.encrypt({plaintext:i,protocolID:[2,`specific linkage revelation ${t.protocolID[0]} ${t.protocolID[1]}`],keyID:t.keyID,counterparty:t.verifier}),{ciphertext:s}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${t.protocolID[0]} ${t.protocolID[1]}`],keyID:t.keyID,counterparty:t.verifier});return{prover:e,verifier:t.verifier,counterparty:t.counterparty,protocolID:t.protocolID,keyID:t.keyID,encryptedLinkage:r,encryptedLinkageProof:s,proofType:0}}async encrypt(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self").encrypt(t.plaintext)}}async decrypt(t,e){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self").decrypt(t.ciphertext)}}async createHmac(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const e=this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self");return{hmac:Z(e.toArray(),t.data)}}async verifyHmac(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const e=this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self"),i=Z(e.toArray(),t.data),r=t.hmac,s=function(t,e){if(t.length!==e.length)return!1;let i=0;for(let r=0;r<t.length;r++)i|=t[r]^e[r];return 0===i}(Wt(i),Wt(r));if(!s){const t=new Error("HMAC is not valid");throw t.code="ERR_INVALID_HMAC",t}return{valid:s}}async createSignature(t){if(null==t.hashToDirectlySign&&null==t.data)throw new Error("args.data or args.hashToDirectlySign must be valid");const e=t.hashToDirectlySign??X(t.data??[]),i=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePrivateKey(t.protocolID,t.keyID,t.counterparty??"anyone");return{signature:Ve(new a(e),i,!0).toDER()}}async verifySignature(t){if(null==t.hashToDirectlyVerify&&null==t.data)throw new Error("args.data or args.hashToDirectlyVerify must be valid");const e=t.hashToDirectlyVerify??X(t.data??[]),i=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePublicKey(t.protocolID,t.keyID,t.counterparty??"self",t.forSelf),r=Ke(new a(e),Be.fromDER(t.signature),i);if(!r){const t=new Error("Signature is not valid");throw t.code="ERR_INVALID_SIGNATURE",t}return{valid:r}}};class or{CWI;constructor(){if("object"!=typeof window)throw new Error("The window.CWI substrate requires a global window object.");if("object"!=typeof window.CWI)throw new Error("The window.CWI interface does not appear to be bound to the window object.");this.CWI=window.CWI}async createAction(t,e){return await this.CWI.createAction(t,e)}async signAction(t,e){return await this.CWI.signAction(t,e)}async abortAction(t,e){return await this.CWI.abortAction(t,e)}async listActions(t,e){return await this.CWI.listActions(t,e)}async internalizeAction(t,e){return await this.CWI.internalizeAction(t,e)}async listOutputs(t,e){return await this.CWI.listOutputs(t,e)}async relinquishOutput(t,e){return await this.CWI.relinquishOutput(t,e)}async getPublicKey(t,e){return await this.CWI.getPublicKey(t,e)}async revealCounterpartyKeyLinkage(t,e){return await this.CWI.revealCounterpartyKeyLinkage(t,e)}async revealSpecificKeyLinkage(t,e){return await this.CWI.revealSpecificKeyLinkage(t,e)}async encrypt(t,e){return await this.CWI.encrypt(t,e)}async decrypt(t,e){return await this.CWI.decrypt(t,e)}async createHmac(t,e){return await this.CWI.createHmac(t,e)}async verifyHmac(t,e){return await this.CWI.verifyHmac(t,e)}async createSignature(t,e){return await this.CWI.createSignature(t,e)}async verifySignature(t,e){return await this.CWI.verifySignature(t,e)}async acquireCertificate(t,e){return await this.CWI.acquireCertificate(t,e)}async listCertificates(t,e){return await this.CWI.listCertificates(t,e)}async proveCertificate(t,e){return await this.CWI.proveCertificate(t,e)}async relinquishCertificate(t,e){return await this.CWI.relinquishCertificate(t,e)}async discoverByIdentityKey(t,e){return await this.CWI.discoverByIdentityKey(t,e)}async discoverByAttributes(t,e){return await this.CWI.discoverByAttributes(t,e)}async isAuthenticated(t,e){return await this.CWI.isAuthenticated(t,e)}async waitForAuthentication(t,e){return await this.CWI.waitForAuthentication(t,e)}async getHeight(t,e){return await this.CWI.getHeight(t,e)}async getHeaderForHeight(t,e){return await this.CWI.getHeaderForHeight(t,e)}async getNetwork(t,e){return await this.CWI.getNetwork(t,e)}async getVersion(t,e){return await this.CWI.getVersion(t,e)}}class cr extends Error{code;isError=!0;constructor(t,e=1,i){super(t),this.code=e,this.name=this.constructor.name,null!=i&&""!==i?this.stack=i:Error.captureStackTrace(this,this.constructor)}static unknownToJson(t){let e;return!0===t.isError&&String(t.name).startsWith("WERR_")?(e={name:t.name,message:t.message,isError:!0},"WERR_REVIEW_ACTIONS"===e.name?(e.reviewActionResults=t.reviewActionResults,e.sendWithResults=t.sendWithResults,e.txid=t.txid,e.tx=t.tx,e.noSendChange=t.noSendChange,e.code=5):"WERR_INVALID_PARAMETER"===e.name?(e.parameter=t.parameter,e.code=6):"WERR_INSUFFICIENT_FUNDS"===e.name&&(e.totalSatoshisNeeded=t.totalSatoshisNeeded,e.moreSatoshisNeeded=t.moreSatoshisNeeded,e.code=7)):e=t instanceof Error?{name:t.constructor.name,message:t.message,isError:!0}:{name:"WERR_UNKNOWN",message:String(t),isError:!0},JSON.stringify(e)}}var hr,ur;!function(t){t[t.unknownError=1]="unknownError",t[t.unsupportedAction=2]="unsupportedAction",t[t.invalidHmac=3]="invalidHmac",t[t.invalidSignature=4]="invalidSignature",t[t.reviewActions=5]="reviewActions",t[t.invalidParameter=6]="invalidParameter",t[t.insufficientFunds=7]="insufficientFunds"}(hr||(hr={}));class dr{domain;constructor(t="*"){if("object"!=typeof window)throw new Error("The XDM substrate requires a global window object.");if("function"!=typeof window.postMessage)throw new Error("The window object does not seem to support postMessage calls.");this.domain=t}async invoke(t,e){return await new Promise((i,r)=>{const s=Zt(We(12)),n=t=>{if("CWI"===t.data.type&&t.isTrusted&&t.data.id===s&&!0!==t.data.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",n),"error"===t.data.status){const e=new cr(t.data.description,t.data.code);r(e)}else i(t.data.result)};window.addEventListener("message",n),window.parent.postMessage({type:"CWI",isInvocation:!0,id:s,call:t,args:e},this.domain)})}async createAction(t){return await this.invoke("createAction",t)}async signAction(t){return await this.invoke("signAction",t)}async abortAction(t){return await this.invoke("abortAction",t)}async listActions(t){return await this.invoke("listActions",t)}async internalizeAction(t){return await this.invoke("internalizeAction",t)}async listOutputs(t){return await this.invoke("listOutputs",t)}async relinquishOutput(t){return await this.invoke("relinquishOutput",t)}async getPublicKey(t){return await this.invoke("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.invoke("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.invoke("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.invoke("encrypt",t)}async decrypt(t){return await this.invoke("decrypt",t)}async createHmac(t){return await this.invoke("createHmac",t)}async verifyHmac(t){return await this.invoke("verifyHmac",t)}async createSignature(t){return await this.invoke("createSignature",t)}async verifySignature(t){return await this.invoke("verifySignature",t)}async acquireCertificate(t){return await this.invoke("acquireCertificate",t)}async listCertificates(t){return await this.invoke("listCertificates",t)}async proveCertificate(t){return await this.invoke("proveCertificate",t)}async relinquishCertificate(t){return await this.invoke("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.invoke("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.invoke("discoverByAttributes",t)}async isAuthenticated(t){return await this.invoke("isAuthenticated",t)}async waitForAuthentication(t){return await this.invoke("waitForAuthentication",t)}async getHeight(t){return await this.invoke("getHeight",t)}async getHeaderForHeight(t){return await this.invoke("getHeaderForHeight",t)}async getNetwork(t){return await this.invoke("getNetwork",t)}async getVersion(t){return await this.invoke("getVersion",t)}}class lr{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(t,e,i,r,s,n,a){this.type=t,this.serialNumber=e,this.subject=i,this.certifier=r,this.revocationOutpoint=s,this.fields=n,this.signature=a}toBinary(t=!0){const e=new se,i=Wt(this.type,"base64");e.write(i);const r=Wt(this.serialNumber,"base64");e.write(r);const s=Wt(this.subject,"hex");e.write(s);const n=Wt(this.certifier,"hex");e.write(n);const[a,o]=this.revocationOutpoint.split("."),c=Wt(a,"hex");e.write(c),e.writeVarIntNum(Number(o));const h=Object.keys(this.fields).sort();e.writeVarIntNum(h.length);for(const t of h){const i=this.fields[t],r=Wt(t,"utf8");e.writeVarIntNum(r.length),e.write(r);const s=Wt(i,"utf8");e.writeVarIntNum(s.length),e.write(s)}if(t&&(this.signature??"").length>0){const t=Wt(this.signature,"hex");e.write(t)}return e.toArray()}static fromBinary(t){const e=new ne(t),i=Zt(e.read(32)),r=Zt(e.read(32)),s=e.read(33),n=jt(s),a=e.read(33),o=jt(a),c=e.read(32),h=`${jt(c)}.${e.readVarIntNum()}`,u=e.readVarIntNum(),d={};for(let t=0;t<u;t++){const t=e.readVarIntNum(),i=e.read(t),r=Yt(i),s=e.readVarIntNum(),n=e.read(s),a=Yt(n);d[r]=a}let l;if(!e.eof()){const t=e.read();l=Be.fromDER(t).toString("hex")}return new lr(i,r,n,o,h,d,l)}async verify(){const t=new ar("anyone"),e=this.toBinary(!1),i=this.signature??"",{valid:r}=await t.verifySignature({signature:Wt(i,"hex"),data:e,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return r}async sign(t){if(null!=this.signature&&this.signature.length>0)throw new Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await t.getPublicKey({identityKey:!0})).publicKey;const e=this.toBinary(!1),{signature:i}=await t.createSignature({data:e,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=jt(i)}static getCertificateFieldEncryptionDetails(t,e){return{protocolID:[2,"certificate field encryption"],keyID:e?`${e} ${t}`:t}}static fromObject(t){return new lr(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,t.signature)}}!function(t){t[t.createAction=1]="createAction",t[t.signAction=2]="signAction",t[t.abortAction=3]="abortAction",t[t.listActions=4]="listActions",t[t.internalizeAction=5]="internalizeAction",t[t.listOutputs=6]="listOutputs",t[t.relinquishOutput=7]="relinquishOutput",t[t.getPublicKey=8]="getPublicKey",t[t.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",t[t.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",t[t.encrypt=11]="encrypt",t[t.decrypt=12]="decrypt",t[t.createHmac=13]="createHmac",t[t.verifyHmac=14]="verifyHmac",t[t.createSignature=15]="createSignature",t[t.verifySignature=16]="verifySignature",t[t.acquireCertificate=17]="acquireCertificate",t[t.listCertificates=18]="listCertificates",t[t.proveCertificate=19]="proveCertificate",t[t.relinquishCertificate=20]="relinquishCertificate",t[t.discoverByIdentityKey=21]="discoverByIdentityKey",t[t.discoverByAttributes=22]="discoverByAttributes",t[t.isAuthenticated=23]="isAuthenticated",t[t.waitForAuthentication=24]="waitForAuthentication",t[t.getHeight=25]="getHeight",t[t.getHeaderForHeight=26]="getHeaderForHeight",t[t.getNetwork=27]="getNetwork",t[t.getVersion=28]="getVersion"}(ur||(ur={}));const fr=ur;class pr{wire;constructor(t){this.wire=t}async transmit(t,e="",i=[]){const r=new se;r.writeUInt8(fr[t]);const s=Wt(e,"utf8");r.writeUInt8(s.length),r.write(s),i.length>0&&r.write(i);const n=r.toArray(),a=await this.wire.transmitToWallet(n),o=new ne(a),c=o.readUInt8();if(0===c)return o.read();{const t=o.readVarIntNum(),e=o.read(t),i=Yt(e),r=o.readVarIntNum(),s=o.read(r),n=Yt(s);throw new cr(i,c,n)}}async createAction(t,e){const i=new se,r=Wt(t.description,"utf8");if(i.writeVarIntNum(r.length),i.write(r),null!=t.inputBEEF?(i.writeVarIntNum(t.inputBEEF.length),i.write(t.inputBEEF)):i.writeVarIntNum(-1),null!=t.inputs){i.writeVarIntNum(t.inputs.length);for(const e of t.inputs){if(i.write(this.encodeOutpoint(e.outpoint)),null!=e.unlockingScript&&""!==e.unlockingScript){const t=Wt(e.unlockingScript,"hex");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1),i.writeVarIntNum(e.unlockingScriptLength??0);const t=Wt(e.inputDescription,"utf8");i.writeVarIntNum(t.length),i.write(t),"number"==typeof e.sequenceNumber?i.writeVarIntNum(e.sequenceNumber):i.writeVarIntNum(-1)}}else i.writeVarIntNum(-1);if(null!=t.outputs){i.writeVarIntNum(t.outputs.length);for(const e of t.outputs){const t=Wt(e.lockingScript,"hex");i.writeVarIntNum(t.length),i.write(t),i.writeVarIntNum(e.satoshis);const r=Wt(e.outputDescription,"utf8");if(i.writeVarIntNum(r.length),i.write(r),null!=e.basket&&""!==e.basket){const t=Wt(e.basket,"utf8");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1);if(null!=e.customInstructions&&""!==e.customInstructions){const t=Wt(e.customInstructions,"utf8");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1);if(null!=e.tags){i.writeVarIntNum(e.tags.length);for(const t of e.tags){const e=Wt(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}}else i.writeVarIntNum(-1)}}else i.writeVarIntNum(-1);if("number"==typeof t.lockTime?i.writeVarIntNum(t.lockTime):i.writeVarIntNum(-1),"number"==typeof t.version?i.writeVarIntNum(t.version):i.writeVarIntNum(-1),null!=t.labels){i.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Wt(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}}else i.writeVarIntNum(-1);if(null!=t.options){if(i.writeInt8(1),"boolean"==typeof t.options.signAndProcess?i.writeInt8(t.options.signAndProcess?1:0):i.writeInt8(-1),"boolean"==typeof t.options.acceptDelayedBroadcast?i.writeInt8(t.options.acceptDelayedBroadcast?1:0):i.writeInt8(-1),"known"===t.options.trustSelf?i.writeInt8(1):i.writeInt8(-1),null!=t.options.knownTxids){i.writeVarIntNum(t.options.knownTxids.length);for(const e of t.options.knownTxids){const t=Wt(e,"hex");i.write(t)}}else i.writeVarIntNum(-1);if("boolean"==typeof t.options.returnTXIDOnly?i.writeInt8(t.options.returnTXIDOnly?1:0):i.writeInt8(-1),"boolean"==typeof t.options.noSend?i.writeInt8(t.options.noSend?1:0):i.writeInt8(-1),null!=t.options.noSendChange){i.writeVarIntNum(t.options.noSendChange.length);for(const e of t.options.noSendChange)i.write(this.encodeOutpoint(e))}else i.writeVarIntNum(-1);if(null!=t.options.sendWith){i.writeVarIntNum(t.options.sendWith.length);for(const e of t.options.sendWith){const t=Wt(e,"hex");i.write(t)}}else i.writeVarIntNum(-1);"boolean"==typeof t.options.randomizeOutputs?i.writeInt8(t.options.randomizeOutputs?1:0):i.writeInt8(-1)}else i.writeInt8(0);const s=await this.transmit("createAction",e,i.toArray()),n=new ne(s),a={};if(1===n.readInt8()){const t=n.read(32);a.txid=jt(t)}if(1===n.readInt8()){const t=n.readVarIntNum();a.tx=n.read(t)}const o=n.readVarIntNum();if(o>=0){a.noSendChange=[];for(let t=0;t<o;t++){const t=this.readOutpoint(n);a.noSendChange.push(t)}}const c=n.readVarIntNum();if(c>=0){a.sendWithResults=[];for(let t=0;t<c;t++){const t=n.read(32),e=jt(t),i=n.readInt8();let r="unproven";1===i?r="unproven":2===i?r="sending":3===i&&(r="failed"),a.sendWithResults.push({txid:e,status:r})}}if(1===n.readInt8()){const t=n.readVarIntNum(),e=n.read(t),i=n.readVarIntNum(),r=n.read(i);a.signableTransaction={tx:e,reference:Zt(r)}}return a}async signAction(t,e){const i=new se,r=Object.keys(t.spends);i.writeVarIntNum(r.length);for(const e of r){i.writeVarIntNum(Number(e));const r=t.spends[Number(e)],s=Wt(r.unlockingScript,"hex");i.writeVarIntNum(s.length),i.write(s),"number"==typeof r.sequenceNumber?i.writeVarIntNum(r.sequenceNumber):i.writeVarIntNum(-1)}const s=Wt(t.reference,"base64");if(i.writeVarIntNum(s.length),i.write(s),null!=t.options)if(i.writeInt8(1),"boolean"==typeof t.options.acceptDelayedBroadcast?i.writeInt8(t.options.acceptDelayedBroadcast?1:0):i.writeInt8(-1),"boolean"==typeof t.options.returnTXIDOnly?i.writeInt8(t.options.returnTXIDOnly?1:0):i.writeInt8(-1),"boolean"==typeof t.options.noSend?i.writeInt8(t.options.noSend?1:0):i.writeInt8(-1),null!=t.options.sendWith){i.writeVarIntNum(t.options.sendWith.length);for(const e of t.options.sendWith){const t=Wt(e,"hex");i.write(t)}}else i.writeVarIntNum(-1);else i.writeInt8(0);const n=await this.transmit("signAction",e,i.toArray()),a=new ne(n),o={};if(1===a.readInt8()){const t=a.read(32);o.txid=jt(t)}if(1===a.readInt8()){const t=a.readVarIntNum();o.tx=a.read(t)}const c=a.readVarIntNum();if(c>=0){o.sendWithResults=[];for(let t=0;t<c;t++){const t=a.read(32),e=jt(t),i=a.readInt8();let r="unproven";1===i?r="unproven":2===i?r="sending":3===i&&(r="failed"),o.sendWithResults.push({txid:e,status:r})}}return o}async abortAction(t,e){return await this.transmit("abortAction",e,Wt(t.reference,"base64")),{aborted:!0}}async listActions(t,e){const i=new se;i.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Wt(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}"any"===t.labelQueryMode?i.writeInt8(1):"all"===t.labelQueryMode?i.writeInt8(2):i.writeInt8(-1);const r=[t.includeLabels,t.includeInputs,t.includeInputSourceLockingScripts,t.includeInputUnlockingScripts,t.includeOutputs,t.includeOutputLockingScripts];for(const t of r)"boolean"==typeof t?i.writeInt8(t?1:0):i.writeInt8(-1);"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const s=await this.transmit("listActions",e,i.toArray()),n=new ne(s),a=n.readVarIntNum(),o=[];for(let t=0;t<a;t++){const t=n.read(32),e=jt(t),i=n.readVarIntNum(),r=n.readInt8();let s;switch(r){case 1:s="completed";break;case 2:s="unprocessed";break;case 3:s="sending";break;case 4:s="unproven";break;case 5:s="unsigned";break;case 6:s="nosend";break;case 7:s="nonfinal";break;case 8:s="failed";break;default:throw new Error(`Unknown status code: ${r}`)}const a=1===n.readInt8(),c=n.readVarIntNum(),h=n.read(c),u={txid:e,satoshis:i,status:s,isOutgoing:a,description:Yt(h),version:0,lockTime:0},d=n.readVarIntNum();if(d>=0){u.labels=[];for(let t=0;t<d;t++){const t=n.readVarIntNum(),e=n.read(t);u.labels.push(Yt(e))}}u.version=n.readVarIntNum(),u.lockTime=n.readVarIntNum();const l=n.readVarIntNum();if(l>=0){u.inputs=[];for(let t=0;t<l;t++){const t=this.readOutpoint(n),e=n.readVarIntNum(),i=n.readVarIntNum();let r;if(i>=0){const t=n.read(i);r=jt(t)}const s=n.readVarIntNum();let a;if(s>=0){const t=n.read(s);a=jt(t)}const o=n.readVarIntNum(),c=n.read(o),h=Yt(c),d=n.readVarIntNum();u.inputs.push({sourceOutpoint:t,sourceSatoshis:e,sourceLockingScript:r,unlockingScript:a,inputDescription:h,sequenceNumber:d})}}const f=n.readVarIntNum();if(f>=0){u.outputs=[];for(let t=0;t<f;t++){const t=n.readVarIntNum(),e=n.readVarIntNum(),i=n.readVarIntNum();let r;if(i>=0){const t=n.read(i);r=jt(t)}const s=1===n.readInt8(),a=n.readVarIntNum(),o=n.read(a),c=Yt(o),h=n.readVarIntNum();let d;if(h>=0){const t=n.read(h);d=Yt(t)}const l=n.readVarIntNum(),f=[];if(l>=0)for(let t=0;t<l;t++){const t=n.readVarIntNum(),e=n.read(t);f.push(Yt(e))}const p=n.readVarIntNum();let g;if(p>=0){const t=n.read(p);g=Yt(t)}u.outputs.push({outputIndex:t,satoshis:e,lockingScript:r,spendable:s,outputDescription:c,basket:d,tags:f,customInstructions:g})}}o.push(u)}return{totalActions:a,actions:o}}async internalizeAction(t,e){const i=new se;i.writeVarIntNum(t.tx.length),i.write(t.tx),i.writeVarIntNum(t.outputs.length);for(const e of t.outputs)if(i.writeVarIntNum(e.outputIndex),"wallet payment"===e.protocol){if(null==e.paymentRemittance)throw new Error("Payment remittance is required for wallet payment");i.writeUInt8(1),i.write(Wt(e.paymentRemittance.senderIdentityKey,"hex"));const t=Wt(e.paymentRemittance.derivationPrefix,"base64");i.writeVarIntNum(t.length),i.write(t);const r=Wt(e.paymentRemittance.derivationSuffix,"base64");i.writeVarIntNum(r.length),i.write(r)}else{i.writeUInt8(2);const t=Wt(e.insertionRemittance?.basket,"utf8");if(i.writeVarIntNum(t.length),i.write(t),"string"==typeof e.insertionRemittance?.customInstructions&&""!==e.insertionRemittance.customInstructions){const t=Wt(e.insertionRemittance.customInstructions,"utf8");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1);if("object"==typeof e.insertionRemittance?.tags){i.writeVarIntNum(e.insertionRemittance.tags.length);for(const t of e.insertionRemittance.tags){const e=Wt(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}}else i.writeVarIntNum(0)}if("object"==typeof t.labels){i.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Wt(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}}else i.writeVarIntNum(-1);const r=Wt(t.description);return i.writeVarIntNum(r.length),i.write(r),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),await this.transmit("internalizeAction",e,i.toArray()),{accepted:!0}}async listOutputs(t,e){const i=new se,r=Wt(t.basket,"utf8");if(i.writeVarIntNum(r.length),i.write(r),"object"==typeof t.tags){i.writeVarIntNum(t.tags.length);for(const e of t.tags){const t=Wt(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}}else i.writeVarIntNum(0);"all"===t.tagQueryMode?i.writeInt8(1):"any"===t.tagQueryMode?i.writeInt8(2):i.writeInt8(-1),"locking scripts"===t.include?i.writeInt8(1):"entire transactions"===t.include?i.writeInt8(2):i.writeInt8(-1),"boolean"==typeof t.includeCustomInstructions?i.writeInt8(t.includeCustomInstructions?1:0):i.writeInt8(-1),"boolean"==typeof t.includeTags?i.writeInt8(t.includeTags?1:0):i.writeInt8(-1),"boolean"==typeof t.includeLabels?i.writeInt8(t.includeLabels?1:0):i.writeInt8(-1),"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const s=await this.transmit("listOutputs",e,i.toArray()),n=new ne(s),a=n.readVarIntNum(),o=n.readVarIntNum();let c;o>=0&&(c=n.read(o));const h=[];for(let t=0;t<a;t++){const t={spendable:!0,outpoint:this.readOutpoint(n),satoshis:n.readVarIntNum()},e=n.readVarIntNum();e>=0&&(t.lockingScript=jt(n.read(e)));const i=n.readVarIntNum();i>=0&&(t.customInstructions=Yt(n.read(i)));const r=n.readVarIntNum();if(-1!==r){const e=[];for(let t=0;t<r;t++){const t=n.readVarIntNum();e.push(Yt(n.read(t)))}t.tags=e}const s=n.readVarIntNum();if(-1!==s){const e=[];for(let t=0;t<s;t++){const t=n.readVarIntNum();e.push(Yt(n.read(t)))}t.labels=e}h.push(t)}return{totalOutputs:a,BEEF:c,outputs:h}}async relinquishOutput(t,e){const i=new se,r=Wt(t.basket,"utf8");return i.writeVarIntNum(r.length),i.write(r),i.write(this.encodeOutpoint(t.output)),await this.transmit("relinquishOutput",e,i.toArray()),{relinquished:!0}}encodeOutpoint(t){const e=new se,[i,r]=t.split(".");return e.write(Wt(i,"hex")),e.writeVarIntNum(Number(r)),e.toArray()}readOutpoint(t){return`${jt(t.read(32))}.${t.readVarIntNum()}`}async getPublicKey(t,e){const i=new se;i.writeUInt8(t.identityKey?1:0),t.identityKey?i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)):(i.write(this.encodeKeyRelatedParams(t.protocolID??=[rr.Silent,"default"],t.keyID??="",t.counterparty,t.privileged,t.privilegedReason)),"boolean"==typeof t.forSelf?i.writeInt8(t.forSelf?1:0):i.writeInt8(-1)),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const r=await this.transmit("getPublicKey",e,i.toArray());return{publicKey:jt(r)}}async revealCounterpartyKeyLinkage(t,e){const i=new se;i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),i.write(Wt(t.counterparty,"hex")),i.write(Wt(t.verifier,"hex"));const r=await this.transmit("revealCounterpartyKeyLinkage",e,i.toArray()),s=new ne(r),n=jt(s.read(33)),a=jt(s.read(33)),o=jt(s.read(33)),c=s.readVarIntNum(),h=Yt(s.read(c)),u=s.readVarIntNum(),d=s.read(u),l=s.readVarIntNum();return{prover:n,verifier:a,counterparty:o,revelationTime:h,encryptedLinkage:d,encryptedLinkageProof:s.read(l)}}async revealSpecificKeyLinkage(t,e){const i=new se;i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.write(Wt(t.verifier,"hex"));const r=await this.transmit("revealSpecificKeyLinkage",e,i.toArray()),s=new ne(r),n=jt(s.read(33)),a=jt(s.read(33)),o=jt(s.read(33)),c=s.readUInt8(),h=s.readVarIntNum(),u=Yt(s.read(h)),d=s.readVarIntNum(),l=Yt(s.read(d)),f=s.readVarIntNum(),p=s.read(f),g=s.readVarIntNum();return{prover:n,verifier:a,counterparty:o,protocolID:[c,u],keyID:l,encryptedLinkage:p,encryptedLinkageProof:s.read(g),proofType:s.readUInt8()}}async encrypt(t,e){const i=new se;return i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.plaintext.length),i.write(t.plaintext),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{ciphertext:await this.transmit("encrypt",e,i.toArray())}}async decrypt(t,e){const i=new se;return i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.ciphertext.length),i.write(t.ciphertext),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{plaintext:await this.transmit("decrypt",e,i.toArray())}}async createHmac(t,e){const i=new se;return i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.writeVarIntNum(t.data.length),i.write(t.data),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{hmac:await this.transmit("createHmac",e,i.toArray())}}async verifyHmac(t,e){const i=new se;return i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.write(t.hmac),i.writeVarIntNum(t.data.length),i.write(t.data),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),await this.transmit("verifyHmac",e,i.toArray()),{valid:!0}}async createSignature(t,e){const i=new se;return i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),"object"==typeof t.data?(i.writeUInt8(1),i.writeVarIntNum(t.data.length),i.write(t.data)):(i.writeUInt8(2),i.write(t.hashToDirectlySign??=[])),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{signature:await this.transmit("createSignature",e,i.toArray())}}async verifySignature(t,e){const i=new se;return i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),"boolean"==typeof t.forSelf?i.writeInt8(t.forSelf?1:0):i.writeInt8(-1),i.writeVarIntNum(t.signature.length),i.write(t.signature),"object"==typeof t.data?(i.writeUInt8(1),i.writeVarIntNum(t.data.length),i.write(t.data)):(i.writeUInt8(2),i.write(t.hashToDirectlyVerify??[])),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),await this.transmit("verifySignature",e,i.toArray()),{valid:!0}}encodeKeyRelatedParams(t,e,i,r,s){const n=new se;n.writeUInt8(t[0]);const a=Wt(t[1],"utf8");n.writeVarIntNum(a.length),n.write(a);const o=Wt(e,"utf8");return n.writeVarIntNum(o.length),n.write(o),"string"!=typeof i?n.writeUInt8(0):"self"===i?n.writeUInt8(11):"anyone"===i?n.writeUInt8(12):n.write(Wt(i,"hex")),n.write(this.encodePrivilegedParams(r,s)),n.toArray()}async acquireCertificate(t,e){const i=new se;i.write(Wt(t.type,"base64")),i.write(Wt(t.certifier,"hex"));const r=Object.entries(t.fields);i.writeVarIntNum(r.length);for(const[t,e]of r){const r=Wt(t,"utf8"),s=Wt(e,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(s.length),i.write(s)}if(i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),i.writeUInt8("direct"===t.acquisitionProtocol?1:2),"direct"===t.acquisitionProtocol){i.write(Wt(t.serialNumber,"base64")),i.write(this.encodeOutpoint(t.revocationOutpoint??""));const e=Wt(t.signature,"hex");i.writeVarIntNum(e.length),i.write(e);const r="certifier"!==t.keyringRevealer?Wt(t.keyringRevealer,"hex"):[11];i.write(r);const s=Object.keys(t.keyringForSubject??{});i.writeVarIntNum(s.length);for(let e=0;e<s.length;e++){const r=Wt(s[e],"utf8");i.writeVarIntNum(r.length),i.write(r);const n=Wt(t.keyringForSubject?.[s[e]],"base64");i.writeVarIntNum(n.length),i.write(n)}}else{const e=Wt(t.certifierUrl,"utf8");i.writeVarIntNum(e.length),i.write(e)}const s=await this.transmit("acquireCertificate",e,i.toArray()),n=lr.fromBinary(s);return{...n,signature:n.signature}}encodePrivilegedParams(t,e){const i=new se;if("boolean"==typeof t?i.writeInt8(t?1:0):i.writeInt8(-1),"string"==typeof e){const t=Wt(e,"utf8");i.writeInt8(t.length),i.write(t)}else i.writeInt8(-1);return i.toArray()}async listCertificates(t,e){const i=new se;i.writeVarIntNum(t.certifiers.length);for(let e=0;e<t.certifiers.length;e++)i.write(Wt(t.certifiers[e],"hex"));i.writeVarIntNum(t.types.length);for(let e=0;e<t.types.length;e++)i.write(Wt(t.types[e],"base64"));"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason));const r=await this.transmit("listCertificates",e,i.toArray()),s=new ne(r),n=s.readVarIntNum(),a=[];for(let t=0;t<n;t++){const t=s.readVarIntNum(),e=s.read(t),i=lr.fromBinary(e),r={};if(1===s.readInt8()){const t=s.readVarIntNum();for(let e=0;e<t;e++){const t=s.readVarIntNum(),e=Yt(s.read(t)),i=s.readVarIntNum();r[e]=Zt(s.read(i))}}const n=s.readVarIntNum();let o;n>0&&(o=Yt(s.read(n))),a.push({...i,signature:i.signature,keyring:r,verifier:o})}return{totalCertificates:n,certificates:a}}async proveCertificate(t,e){const i=new se,r=Wt(t.certificate.type,"base64");i.write(r);const s=Wt(t.certificate.subject,"hex");i.write(s);const n=Wt(t.certificate.serialNumber,"base64");i.write(n);const a=Wt(t.certificate.certifier,"hex");i.write(a);const o=this.encodeOutpoint(t.certificate.revocationOutpoint??"");i.write(o);const c=Wt(t.certificate.signature,"hex");i.writeVarIntNum(c.length),i.write(c);const h=Object.entries(t.certificate.fields??{});i.writeVarIntNum(h.length);for(const[t,e]of h){const r=Wt(t,"utf8"),s=Wt(e,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(s.length),i.write(s)}i.writeVarIntNum(t.fieldsToReveal.length);for(const e of t.fieldsToReveal){const t=Wt(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}i.write(Wt(t.verifier,"hex")),i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason));const u=await this.transmit("proveCertificate",e,i.toArray()),d=new ne(u),l=d.readVarIntNum(),f={};for(let t=0;t<l;t++){const t=d.readVarIntNum(),e=Yt(d.read(t)),i=d.readVarIntNum();f[e]=Zt(d.read(i))}return{keyringForVerifier:f}}async relinquishCertificate(t,e){const i=new se,r=Wt(t.type,"base64");i.write(r);const s=Wt(t.serialNumber,"base64");i.write(s);const n=Wt(t.certifier,"hex");return i.write(n),await this.transmit("relinquishCertificate",e,i.toArray()),{relinquished:!0}}parseDiscoveryResult(t){const e=new ne(t),i=e.readVarIntNum(),r=[];for(let t=0;t<i;t++){const t=e.readVarIntNum(),i=e.read(t),s=lr.fromBinary(i),n=e.readVarIntNum(),a=Yt(e.read(n)),o=e.readVarIntNum(),c=Yt(e.read(o)),h=e.readVarIntNum(),u=Yt(e.read(h)),d=e.readUInt8(),l={},f=e.readVarIntNum();for(let t=0;t<f;t++){const t=e.readVarIntNum(),i=Yt(e.read(t)),r=e.readVarIntNum();l[i]=e.read(r)}const p={},g=e.readVarIntNum();for(let t=0;t<g;t++){const t=e.readVarIntNum(),i=Yt(e.read(t)),r=e.readVarIntNum();p[i]=Yt(e.read(r))}r.push({...s,signature:s.signature,certifierInfo:{iconUrl:c,name:a,description:u,trust:d},publiclyRevealedKeyring:l,decryptedFields:p})}return{totalCertificates:i,certificates:r}}async discoverByIdentityKey(t,e){const i=new se;i.write(Wt(t.identityKey,"hex")),"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const r=await this.transmit("discoverByIdentityKey",e,i.toArray());return this.parseDiscoveryResult(r)}async discoverByAttributes(t,e){const i=new se,r=Object.keys(t.attributes);i.writeVarIntNum(r.length);for(let e=0;e<r.length;e++)i.writeVarIntNum(r[e].length),i.write(Wt(r[e],"utf8")),i.writeVarIntNum(t.attributes[r[e]].length),i.write(Wt(t.attributes[r[e]],"utf8"));"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const s=await this.transmit("discoverByAttributes",e,i.toArray());return this.parseDiscoveryResult(s)}async isAuthenticated(t,e){return{authenticated:1===(await this.transmit("isAuthenticated",e))[0]}}async waitForAuthentication(t,e){return await this.transmit("waitForAuthentication",e),{authenticated:!0}}async getHeight(t,e){const i=await this.transmit("getHeight",e);return{height:new ne(i).readVarIntNum()}}async getHeaderForHeight(t,e){const i=new se;i.writeVarIntNum(t.height);const r=await this.transmit("getHeaderForHeight",e,i.toArray());return{header:jt(r)}}async getNetwork(t,e){return{network:0===(await this.transmit("getNetwork",e))[0]?"mainnet":"testnet"}}async getVersion(t,e){const i=await this.transmit("getVersion",e);return{version:Yt(i)}}}class gr{baseUrl;httpClient;originator;constructor(t,e="http://localhost:3301",i=fetch){this.baseUrl=e,this.httpClient=i,this.originator=t}async transmitToWallet(t){const e=new ne(t),i=e.readUInt8(),r=fr[i];if(void 0===r||""===r)throw new Error(`Invalid call code: ${i}`);const s=e.readUInt8();let n;if(s>0){const t=e.read(s);n=Yt(t)}const a=e.read(),o=await fetch(`${this.baseUrl}/${r}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:n??""},body:new Uint8Array(a)}),c=await o.arrayBuffer();return Array.from(new Uint8Array(c))}}class yr extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(t,e,i,r,s){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=t,this.sendWithResults=e,this.txid=i,this.tx=r,this.noSendChange=s,this.code=5,this.name=this.constructor.name}}class br extends Error{parameter;code;isError=!0;constructor(t,e){super(`The ${t} parameter must be ${e??"valid."}`),this.parameter=t,this.code=6,this.name=this.constructor.name}}const mr=br;class wr extends Error{totalSatoshisNeeded;moreSatoshisNeeded;code;isError=!0;constructor(t,e){super(`Insufficient funds in the available inputs to cover the cost of the required outputs and the transaction fee (${e} more satoshis are needed, for a total of ${t}), plus whatever would be required in order to pay the fee to unlock and spend the outputs used to provide the additional satoshis.`),this.totalSatoshisNeeded=t,this.moreSatoshisNeeded=e,this.code=7,this.name=this.constructor.name}}const vr=wr;class Ir{baseUrl;httpClient;originator;api;constructor(t,e="http://localhost:3321",i=fetch){this.baseUrl=e,this.originator=t,this.httpClient=i;const r="undefined"!=typeof window&&"undefined"!=typeof document&&"file://"!==window?.origin;this.api=async(t,e)=>{const s=!r&&this.originator?function(t,e="http"){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(t))try{return new URL(t).origin}catch{}try{return new URL(`${e}://${t}`).origin}catch{throw new Error(`Invalid originator value: ${t}`)}}(this.originator,"http"):void 0;r||void 0!==s||console.error("Originator is required in Node.js environments");const n=await await i(`${this.baseUrl}/${t}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...s?{Origin:s}:{},...s?{Originator:s}:{}},body:JSON.stringify(e)}),a=await n.json();if(!n.ok){if(400===n.status&&a.isError){let t;switch(a.code){case 5:t=new yr(a.reviewActionResults,a.sendWithResults,a.txid,a.tx,a.noSendChange);break;case 6:t=new br(a.parameter),t.message=a.message;break;case 7:t=new vr(a.totalSatoshisNeeded,a.moreSatoshisNeeded)}if(t)throw t}const i={call:t,args:e,message:a.message??`HTTP Client error ${n.status}`};throw new Error(JSON.stringify(i))}return a}}async createAction(t){return await this.api("createAction",t)}async signAction(t){return await this.api("signAction",t)}async abortAction(t){return await this.api("abortAction",t)}async listActions(t){return await this.api("listActions",t)}async internalizeAction(t){return await this.api("internalizeAction",t)}async listOutputs(t){return await this.api("listOutputs",t)}async relinquishOutput(t){return await this.api("relinquishOutput",t)}async getPublicKey(t){return await this.api("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.api("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.api("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.api("encrypt",t)}async decrypt(t){return await this.api("decrypt",t)}async createHmac(t){return await this.api("createHmac",t)}async verifyHmac(t){return await this.api("verifyHmac",t)}async createSignature(t){return await this.api("createSignature",t)}async verifySignature(t){return await this.api("verifySignature",t)}async acquireCertificate(t){return await this.api("acquireCertificate",t)}async listCertificates(t){return await this.api("listCertificates",t)}async proveCertificate(t){return await this.api("proveCertificate",t)}async relinquishCertificate(t){return await this.api("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.api("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.api("discoverByAttributes",t)}async isAuthenticated(t){return await this.api("isAuthenticated",t)}async waitForAuthentication(t){return await this.api("waitForAuthentication",t)}async getHeight(t){return await this.api("getHeight",t)}async getHeaderForHeight(t){return await this.api("getHeaderForHeight",t)}async getNetwork(t){return await this.api("getNetwork",t)}async getVersion(t){return await this.api("getVersion",t)}}class kr{domain;constructor(t="*"){if("object"!=typeof window)throw new Error("The XDM substrate requires a global window object.");if(!window.hasOwnProperty("ReactNativeWebView"))throw new Error("The window object does not have a ReactNativeWebView property.");if("function"!=typeof window.ReactNativeWebView.postMessage)throw new Error("The window.ReactNativeWebView property does not seem to support postMessage calls.");this.domain=t}async invoke(t,e){return await new Promise((i,r)=>{const s=Zt(We(12)),n=t=>{const e=JSON.parse(t.data);if("CWI"===e.type&&e.id===s&&!0!==e.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",n),"error"===e.status){const t=new cr(e.description,e.code);r(t)}else i(e.result)};window.addEventListener("message",n),window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:s,call:t,args:e}))})}async createAction(t){return await this.invoke("createAction",t)}async signAction(t){return await this.invoke("signAction",t)}async abortAction(t){return await this.invoke("abortAction",t)}async listActions(t){return await this.invoke("listActions",t)}async internalizeAction(t){return await this.invoke("internalizeAction",t)}async listOutputs(t){return await this.invoke("listOutputs",t)}async relinquishOutput(t){return await this.invoke("relinquishOutput",t)}async getPublicKey(t){return await this.invoke("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.invoke("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.invoke("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.invoke("encrypt",t)}async decrypt(t){return await this.invoke("decrypt",t)}async createHmac(t){return await this.invoke("createHmac",t)}async verifyHmac(t){return await this.invoke("verifyHmac",t)}async createSignature(t){return await this.invoke("createSignature",t)}async verifySignature(t){return await this.invoke("verifySignature",t)}async acquireCertificate(t){return await this.invoke("acquireCertificate",t)}async listCertificates(t){return await this.invoke("listCertificates",t)}async proveCertificate(t){return await this.invoke("proveCertificate",t)}async relinquishCertificate(t){return await this.invoke("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.invoke("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.invoke("discoverByAttributes",t)}async isAuthenticated(t){return await this.invoke("isAuthenticated",t)}async waitForAuthentication(t){return await this.invoke("waitForAuthentication",t)}async getHeight(t){return await this.invoke("getHeight",t)}async getHeaderForHeight(t){return await this.invoke("getHeaderForHeight",t)}async getNetwork(t){return await this.invoke("getNetwork",t)}async getVersion(t){return await this.invoke("getVersion",t)}}function Sr(t){const[e,i]=t.split(".");return{txid:e,vout:Number(i)}}function Er(t){return t??!0}function xr(t){return t??!1}function Pr(t){return t??0}function _r(t){return t??[]}function Ar(t,e,i,r){if(void 0!==t)return Cr(t,e,i,r)}function Nr(t,e,i){if(void 0===t||!Number.isInteger(t)||t<0||t>21e14)throw new mr(e,"a valid number of satoshis");if(void 0!==i&&t<i)throw new mr(e,`at least ${i} satoshis.`);return t}function Or(t,e,i,r,s){if(void 0===t){if(void 0!==i)return i;throw new mr(e,"a valid integer")}if(!Number.isInteger(t))throw new mr(e,"an integer");if(t=Number(t),void 0!==r&&t<r)throw new mr(e,`at least ${r} length.`);if(void 0!==s&&t>s)throw new mr(e,`no more than ${s} length.`);return t}function Tr(t,e){return Or(t,e,0,0)}function Cr(t,e,i,r){const s=Wt(t,"utf8").length;if(void 0!==i&&s<i)throw new mr(e,`at least ${i} length.`);if(void 0!==r&&s>r)throw new mr(e,`no more than ${r} length.`);return t}function Rr(t){if(void 0!==t)return Br(t)}function Br(t){return Fr(t,"basket",1,300)}function Lr(t){return Fr(t,"label",1,300)}function Mr(t){return Fr(t,"tag",1,300)}function Fr(t,e,i,r){t=t.trim().toLowerCase();const s=Wt(t,"utf8").length;if(void 0!==i&&s<i)throw new mr(e,`at least ${i} length.`);if(void 0!==r&&s>r)throw new mr(e,`no more than ${r} length.`);return t}function Ur(t,e,i,r){if(void 0!==t)return Dr(t,e,i,r)}function Dr(t,e,i,r){if(0===(t=t.trim()).length)throw new mr(e,"valid base64 string");let s=0;for(let i=0;i<t.length;i++){const r=t.charCodeAt(i);if(!(r>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r)){if(61!==r)throw new mr(e,"valid base64 string");if(i<t.length-2)throw new mr(e,"valid base64 string");s++}}if(s>2)throw new mr(e,"valid base64 string");if(s>0&&t.length%4!=0)throw new mr(e,"valid base64 string");const n=t.length%4;if(0!==n&&n!==4-s)throw new mr(e,"valid base64 string");const a=t.length-s,o=Math.floor(3*a/4);if(void 0!==i&&o<i)throw new mr(e,`at least ${i} bytes`);if(void 0!==r&&o>r)throw new mr(e,`no more than ${r} bytes`);return t}function Hr(t,e,i,r){if(void 0!==t)return qr(t,e,i,r)}function qr(t,e,i,r){if((t=t.trim().toLowerCase()).length%2==1)throw new mr(e,`even length, not ${t.length}.`);if(!/^[0-9A-Fa-f]+$/.test(t))throw new mr(e,"hexadecimal string.");if(void 0!==i&&t.length<i)throw new mr(e,`at least ${i} length.`);if(void 0!==r&&t.length>r)throw new mr(e,`no more than ${r} length.`);return t}function Vr(t){const e=null!=t?t:{};return{signAndProcess:Er(e.signAndProcess),acceptDelayedBroadcast:Er(e.acceptDelayedBroadcast),knownTxids:_r(e.knownTxids),returnTXIDOnly:xr(e.returnTXIDOnly),noSend:xr(e.noSend),noSendChange:_r(e.noSendChange).map(t=>Sr(t)),sendWith:_r(e.sendWith),randomizeOutputs:Er(e.randomizeOutputs)}}function Kr(t){const e=null!=t?t:{};return{acceptDelayedBroadcast:Er(e.acceptDelayedBroadcast),returnTXIDOnly:xr(e.returnTXIDOnly),noSend:xr(e.noSend),sendWith:_r(e.sendWith)}}function $r(t){if(void 0!==t)return{derivationPrefix:Dr(t.derivationPrefix,"derivationPrefix"),derivationSuffix:Dr(t.derivationSuffix,"derivationSuffix"),senderIdentityKey:qr(t.senderIdentityKey,"senderIdentityKey")}}function jr(t){if(void 0!==t)return{basket:Br(t.basket),customInstructions:Ar(t.customInstructions,"customInstructions",0,1e3),tags:_r(t.tags).map(t=>Mr(t))}}function zr(t,e){const i=t.split(".");if(2!==i.length||!Number.isInteger(Number(i[1])))throw new mr(e,"txid as hex string and numeric output index joined with '.'");return`${qr(i[0],`${e} txid`,void 0,64)}.${Tr(Number(i[1]),`${e} vout`)}`}function Wr(t){for(const e of Object.keys(t))Cr(e,"field name",1,50);return t}const Gr="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";class Xr{substrate;originator;constructor(t="auto",e){"Cicada"===t&&(t=new pr(new gr(e))),"window.CWI"===t&&(t=new or),"XDM"===t&&(t=new dr),"json-api"===t&&(t=new Ir(e)),"react-native"===t&&(t=new kr(e)),"secure-json-api"===t&&(t=new Ir(e,"https://localhost:2121")),this.substrate=t,this.originator=e}async connectToSubstrate(){if("object"==typeof this.substrate)return;const t=async(t,e)=>{try{const i=t();let r;return r="number"==typeof e?await Promise.race([i.getVersion({}),new Promise((t,i)=>setTimeout(()=>i(new Error("Timed out.")),e))]):await i.getVersion({}),"object"!=typeof r||"string"!=typeof r.version?{success:!1}:{success:!0,sub:i}}catch{return{success:!1}}},e=[t(()=>new or),t(()=>new pr(new gr(this.originator))),t(()=>new Ir(this.originator,"https://localhost:2121")),t(()=>new Ir(this.originator)),t(()=>new kr(this.originator))],i=(await Promise.allSettled(e)).filter(t=>"fulfilled"===t.status&&t.value.success&&void 0!==t.value.sub).map(t=>t.value.sub);if(i.length>0)return void(this.substrate=i[0]);const r=await t(()=>new dr,200);if(!r.success||void 0===r.sub)throw new Error("No wallet available over any communication substrate. Install a BSV wallet today!");this.substrate=r.sub}async createAction(t){return function(t,e){const i={description:Cr(t.description,"description",5,2e3),inputBEEF:t.inputBEEF,inputs:_r(t.inputs).map(t=>function(t){if(void 0===t.unlockingScript&&void 0===t.unlockingScriptLength)throw new mr("unlockingScript, unlockingScriptLength","at least one valid value.");const e=Hr(t.unlockingScript,"unlockingScript"),i=t.unlockingScriptLength??(null!=e?e.length/2:0);if(e&&i!==e.length/2)throw new mr("unlockingScriptLength","length unlockingScript if both valid.");var r;return{outpoint:Sr(t.outpoint),inputDescription:Cr(t.inputDescription,"inputDescription",5,2e3),unlockingScript:e,unlockingScriptLength:i,sequenceNumber:(r=t.sequenceNumber,r??4294967295)}}(t)),outputs:_r(t.outputs).map(t=>function(t){return{lockingScript:qr(t.lockingScript,"lockingScript"),satoshis:Nr(t.satoshis,"satoshis"),outputDescription:Cr(t.outputDescription,"outputDescription",5,2e3),basket:Rr(t.basket),customInstructions:t.customInstructions,tags:_r(t.tags).map(t=>Mr(t))}}(t)),lockTime:Pr(t.lockTime),version:(r=t.version,r??1),labels:_r(t.labels?.map(t=>Lr(t))),options:Vr(t.options),logger:e,isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!1,isRemixChange:!1,isSignAction:!1,randomVals:void 0,includeAllSourceTransactions:!1,isTestWerrReviewActions:!1};var r;i.isTestWerrReviewActions=i.labels.includes(Gr),i.isSendWith=i.options.sendWith.length>0,i.isRemixChange=!i.isSendWith&&0===i.inputs.length&&0===i.outputs.length,i.isNewTx=i.isRemixChange||i.inputs.length>0||i.outputs.length>0,i.isSignAction=i.isNewTx&&(!i.options.signAndProcess||i.inputs.some(t=>void 0===t.unlockingScript)),i.isDelayed=i.options.acceptDelayedBroadcast,i.isNoSend=i.options.noSend}(t),await this.connectToSubstrate(),await this.substrate.createAction(t,this.originator)}async signAction(t){return function(t){const e={spends:t.spends,reference:t.reference,options:Kr(t.options),isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!0,isRemixChange:!1,isTestWerrReviewActions:!1};e.isSendWith=e.options.sendWith.length>0,e.isDelayed=e.options.acceptDelayedBroadcast,e.isNoSend=e.options.noSend}(t),await this.connectToSubstrate(),await this.substrate.signAction(t,this.originator)}async abortAction(t){return function(t){Dr(t.reference,"reference")}(t),await this.connectToSubstrate(),await this.substrate.abortAction(t,this.originator)}async listActions(t){return function(t){let e;if(void 0===t.labelQueryMode||"any"===t.labelQueryMode)e="any";else{if("all"!==t.labelQueryMode)throw new mr("labelQueryMode","undefined, 'any', or 'all'");e="all"}(null!=t.labels?t.labels:[]).map(t=>Lr(t)),xr(t.includeLabels),xr(t.includeInputs),xr(t.includeInputSourceLockingScripts),xr(t.includeInputUnlockingScripts),xr(t.includeOutputs),xr(t.includeOutputLockingScripts),Or(t.limit,"limit",10,1,1e4),Or(t.offset,"offset",0,0),Er(t.seekPermission)}(t),await this.connectToSubstrate(),await this.substrate.listActions(t,this.originator)}async internalizeAction(t){return function(t){const e={tx:t.tx,outputs:t.outputs.map(t=>function(t){if("basket insertion"!==t.protocol&&"wallet payment"!==t.protocol)throw new mr("protocol","'basket insertion' or 'wallet payment'");return{outputIndex:Tr(t.outputIndex,"outputIndex"),protocol:t.protocol,paymentRemittance:$r(t.paymentRemittance),insertionRemittance:jr(t.insertionRemittance)}}(t)),description:Cr(t.description,"description",5,2e3),labels:(null!=t.labels?t.labels:[]).map(t=>Lr(t)),seekPermission:Er(t.seekPermission)};try{if(er.fromBinary(e.tx).txs.length<1)throw new mr("tx","at least one transaction to internalize an output from")}catch{throw new mr("tx","valid with at least one transaction to internalize an output from")}if(e.outputs.length<1)throw new mr("outputs","at least one output to internalize from the transaction")}(t),await this.connectToSubstrate(),await this.substrate.internalizeAction(t,this.originator)}async listOutputs(t){return function(t){let e;if(void 0===t.tagQueryMode||"any"===t.tagQueryMode)e="any";else{if("all"!==t.tagQueryMode)throw new mr("tagQueryMode","undefined, 'any', or 'all'");e="all"}Cr(t.basket,"basket",1,300),(null!=t.tags?t.tags:[]).map(t=>Cr(t,"tag",1,300)),t.include,t.include,xr(t.includeCustomInstructions),xr(t.includeTags),xr(t.includeLabels),Or(t.limit,"limit",10,1,1e4),Or(t.offset,"offset",0,void 0,void 0),Er(t.seekPermission)}(t),await this.connectToSubstrate(),await this.substrate.listOutputs(t,this.originator)}async relinquishOutput(t){return function(t){Br(t.basket),zr(t.output,"output")}(t),await this.connectToSubstrate(),await this.substrate.relinquishOutput(t,this.originator)}async getPublicKey(t){return await this.connectToSubstrate(),await this.substrate.getPublicKey(t,this.originator)}async revealCounterpartyKeyLinkage(t){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(t,this.originator)}async revealSpecificKeyLinkage(t){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(t,this.originator)}async encrypt(t){return await this.connectToSubstrate(),await this.substrate.encrypt(t,this.originator)}async decrypt(t){return await this.connectToSubstrate(),await this.substrate.decrypt(t,this.originator)}async createHmac(t){return await this.connectToSubstrate(),await this.substrate.createHmac(t,this.originator)}async verifyHmac(t){return await this.connectToSubstrate(),await this.substrate.verifyHmac(t,this.originator)}async createSignature(t){return await this.connectToSubstrate(),await this.substrate.createSignature(t,this.originator)}async verifySignature(t){return await this.connectToSubstrate(),await this.substrate.verifySignature(t,this.originator)}async acquireCertificate(t){if("direct"===t.acquisitionProtocol)!function(t){if("direct"!==t.acquisitionProtocol)throw new Error("Only acquire direct certificate requests allowed here.");if(!t.serialNumber)throw new mr("serialNumber",'valid when acquisitionProtocol is "direct"');if(!t.signature)throw new mr("signature",'valid when acquisitionProtocol is "direct"');if(!t.revocationOutpoint)throw new mr("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!t.keyringRevealer)throw new mr("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null==t.keyringForSubject)throw new mr("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(t.privileged&&!t.privilegedReason)throw new mr("privilegedReason","valid when 'privileged' is true ");var e;Dr(t.type,"type"),Dr(t.serialNumber,"serialNumber"),qr(t.certifier,"certifier"),zr(t.revocationOutpoint,"revocationOutpoint"),Wr(t.fields),qr(t.signature,"signature"),"certifier"===(e=t.keyringRevealer)||qr(e,"keyringRevealer"),function(t,e){for(const i of Object.keys(t))Cr(i,`${e} field name`,1,50),Dr(t[i],`${e} field value`)}(t.keyringForSubject,"keyringForSubject"),xr(t.privileged),Ar(t.privilegedReason,"privilegedReason",5,50)}(t);else{if("issuance"!==t.acquisitionProtocol)throw new br("acquisitionProtocol",`valid. ${String(t.acquisitionProtocol)} is unrecognized.`);!function(t){if("issuance"!==t.acquisitionProtocol)throw new Error("Only acquire certificate via issuance requests allowed here.");if(t.serialNumber)throw new mr("serialNumber",'valid when acquisitionProtocol is "direct"');if(t.signature)throw new mr("signature",'valid when acquisitionProtocol is "direct"');if(t.revocationOutpoint)throw new mr("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(t.keyringRevealer)throw new mr("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null!=t.keyringForSubject)throw new mr("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!t.certifierUrl)throw new mr("certifierUrl",'valid when acquisitionProtocol is "issuance"');if(t.privileged&&!t.privilegedReason)throw new mr("privilegedReason","valid when 'privileged' is true ");Dr(t.type,"type"),qr(t.certifier,"certifier"),t.certifierUrl,Wr(t.fields),xr(t.privileged),Ar(t.privilegedReason,"privilegedReason",5,50)}(t)}return await this.connectToSubstrate(),await this.substrate.acquireCertificate(t,this.originator)}async listCertificates(t){return function(t){_r(t.certifiers.map(t=>qr(t.trim(),"certifiers"))),_r(t.types.map(t=>Dr(t.trim(),"types"))),Or(t.limit,"limit",10,1,1e4),Tr(Pr(t.offset),"offset"),xr(t.privileged),Ar(t.privilegedReason,"privilegedReason",5,50)}(t),await this.connectToSubstrate(),await this.substrate.listCertificates(t,this.originator)}async proveCertificate(t){return function(t){if(t.privileged&&!t.privilegedReason)throw new mr("privilegedReason","valid when 'privileged' is true ");Ur(t.certificate.type,"certificate.type"),Ur(t.certificate.serialNumber,"certificate.serialNumber"),Hr(t.certificate.certifier,"certificate.certifier"),Hr(t.certificate.subject,"certificate.subject"),function(t,e){if(void 0!==t)zr(t,e)}(t.certificate.revocationOutpoint,"certificate.revocationOutpoint"),Hr(t.certificate.signature,"certificate.signature"),_r(t.fieldsToReveal).map(t=>Cr(t,`fieldsToReveal ${t}`,1,50)),qr(t.verifier,"verifier"),xr(t.privileged),Ar(t.privilegedReason,"privilegedReason",5,50)}(t),await this.connectToSubstrate(),await this.substrate.proveCertificate(t,this.originator)}async relinquishCertificate(t){return function(t){Dr(t.type,"type"),Dr(t.serialNumber,"serialNumber"),qr(t.certifier,"certifier")}(t),await this.connectToSubstrate(),await this.substrate.relinquishCertificate(t,this.originator)}async discoverByIdentityKey(t){return function(t){qr(t.identityKey,"identityKey",66,66),Or(t.limit,"limit",10,1,1e4),Tr(Pr(t.offset),"offset"),xr(t.seekPermission)}(t),await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(t,this.originator)}async discoverByAttributes(t){return function(t){(function(t){for(const e of Object.keys(t))Cr(e,`field name ${e}`,1,50)})(t.attributes),Or(t.limit,"limit",10,1,1e4),Tr(Pr(t.offset),"offset"),xr(t.seekPermission)}(t),await this.connectToSubstrate(),await this.substrate.discoverByAttributes(t,this.originator)}async isAuthenticated(t={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(t,this.originator)}async waitForAuthentication(t={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(t,this.originator)}async getHeight(t={}){return await this.connectToSubstrate(),await this.substrate.getHeight(t,this.originator)}async getHeaderForHeight(t){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(t,this.originator)}async getNetwork(t={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(t,this.originator)}async getVersion(t={}){return await this.connectToSubstrate(),await this.substrate.getVersion(t,this.originator)}}class Yr extends lr{keyring;decryptedFields;constructor(t,e,i,r,s,n,a,o,c){super(t,e,i,r,s,n,o),this.keyring=a,this.decryptedFields=c}static fromCertificate(t,e){return new Yr(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,e,t.signature)}async decryptFields(t,e,i,r){if(null==this.keyring||0===Object.keys(this.keyring).length)throw new Error("A keyring is required to decrypt certificate fields for the verifier.");try{const s={};for(const n in this.keyring){const{plaintext:a}=await t.decrypt({ciphertext:Wt(this.keyring[n],"base64"),...lr.getCertificateFieldEncryptionDetails(n,this.serialNumber),counterparty:this.subject,privileged:e,privilegedReason:i},r),o=new wi(a).decrypt(Wt(this.fields[n],"base64"));s[n]=Yt(o)}return s}catch(t){throw new Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(t instanceof Error?t.message:t)}`)}}}class Jr{sessionNonceToSession;identityKeyToNonces;constructor(){this.sessionNonceToSession=new Map,this.identityKeyToNonces=new Map}addSession(t){if("string"!=typeof t.sessionNonce)throw new Error("Invalid session: sessionNonce is required to add a session.");if(this.sessionNonceToSession.set(t.sessionNonce,t),"string"==typeof t.peerIdentityKey){let e=this.identityKeyToNonces.get(t.peerIdentityKey);null==e&&(e=new Set,this.identityKeyToNonces.set(t.peerIdentityKey,e)),e.add(t.sessionNonce)}}updateSession(t){this.removeSession(t),this.addSession(t)}getSession(t){const e=this.sessionNonceToSession.get(t);if(null!=e)return e;const i=this.identityKeyToNonces.get(t);if(null==i||0===i.size)return;let r;for(const t of i){const e=this.sessionNonceToSession.get(t);null!=e&&(null==r||(e.lastUpdate??0)>(r.lastUpdate??0))&&(r=e)}return r}removeSession(t){if("string"==typeof t.sessionNonce&&this.sessionNonceToSession.delete(t.sessionNonce),"string"==typeof t.peerIdentityKey){const e=this.identityKeyToNonces.get(t.peerIdentityKey);null!=e&&(e.delete(t.sessionNonce??""),0===e.size&&this.identityKeyToNonces.delete(t.peerIdentityKey))}}hasSession(t){if(this.sessionNonceToSession.has(t))return!0;const e=this.identityKeyToNonces.get(t);return!(null==e)&&e.size>0}}async function Zr(t,e,i="self",r){const s=Wt(t,"base64"),n=s.slice(0,16),a=s.slice(16),{valid:o}=await e.verifyHmac({data:n,hmac:a,protocolID:[2,"server hmac"],keyID:Yt(n),counterparty:i},r);return o}async function Qr(t,e="self",i){const r=We(16),{hmac:s}=await t.createHmac({protocolID:[2,"server hmac"],keyID:Yt(r),data:r,counterparty:e},i);return Zt([...r,...s])}const ts=async(t,e,i,r)=>{const s=await t.listCertificates({certifiers:e.certifiers,types:Object.keys(e.types)},r);return await Promise.all(s.certificates.map(async s=>{const{keyringForVerifier:n}=await t.proveCertificate({certificate:s,fieldsToReveal:e.types[s.type],verifier:i},r);return new Yr(s.type,s.serialNumber,s.subject,s.certifier,s.revocationOutpoint,s.fields,n,s.signature)}))},es=async(t,e,i,r)=>{if(null==e.certificates||0===e.certificates.length)throw new Error("No certificates were provided in the AuthMessage.");await Promise.all(e.certificates.map(async s=>{if(s.subject!==e.identityKey)throw new Error(`The subject of one of your certificates ("${s.subject}") is not the same as the request sender ("${e.identityKey}").`);const n=new Yr(s.type,s.serialNumber,s.subject,s.certifier,s.revocationOutpoint,s.fields,s.keyring,s.signature);if(!await n.verify())throw new Error(`The signature for the certificate with serial number ${n.serialNumber} is invalid!`);if(null!=i){const{certifiers:t,types:e}=i;if(!t.includes(n.certifier))throw new Error(`Certificate with serial number ${n.serialNumber} has an unrequested certifier: ${n.certifier}`);if(null==e[n.type])throw new Error(`Certificate with type ${n.type} was not requested`)}await n.decryptFields(t,void 0,void 0,r)}))},is="0.1",rs="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class ss{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;certificateValidationPromises=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;identityPublicKey;constructor(t,e,i,r,s,n){this.wallet=t,this.originator=n,this.transport=e,this.certificatesToRequest=i??{certifiers:[],types:{}},this.transport.onData(this.handleIncomingMessage.bind(this)).catch(t=>{throw t}),this.sessionManager=null!=r?r:new Jr,this.autoPersistLastSession=!1!==s}async toPeer(t,e){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof e&&(e=this.lastInteractedWithPeer);const i=await this.getAuthenticatedSession(e);if(null==i.peerIdentityKey)throw new Error("Peer identity is not established");if(!0===i.certificatesRequired&&!0!==i.certificatesValidated)throw new Error("Cannot send general message before certificate validation is complete");const r=Zt(We(32)),{signature:s}=await this.wallet.createSignature({data:t,protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),n={version:is,messageType:"general",identityKey:await this.getIdentityPublicKey(),nonce:r,yourNonce:i.peerNonce,payload:t,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(n)}catch(t){this.propagateTransportError(i.peerIdentityKey,t)}}async requestCertificates(t,e){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof e&&(e=this.lastInteractedWithPeer);const i=await this.getAuthenticatedSession(e),r=Zt(We(32)),{signature:s}=await this.wallet.createSignature({data:ss.utf8ToBytes(JSON.stringify(t)),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),n={version:is,messageType:"certificateRequest",identityKey:await this.getIdentityPublicKey(),nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:t,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(n)}catch(t){this.propagateTransportError(i.peerIdentityKey,t)}}async getAuthenticatedSession(t){if(void 0===this.transport)throw new Error("Peer transport is not connected!");let e;if("string"==typeof t&&(e=this.sessionManager.getSession(t)),null==e||!e.isAuthenticated){const i=await this.initiateHandshake(t);if(e=this.sessionManager.getSession(i),null==e||!e.isAuthenticated)throw new Error("Unable to establish mutual authentication with peer!")}return e}listenForGeneralMessages(t){const e=this.callbackIdCounter++;return this.onGeneralMessageReceivedCallbacks.set(e,t),e}stopListeningForGeneralMessages(t){this.onGeneralMessageReceivedCallbacks.delete(t)}listenForCertificatesReceived(t){const e=this.callbackIdCounter++;return this.onCertificatesReceivedCallbacks.set(e,t),e}stopListeningForCertificatesReceived(t){this.onCertificatesReceivedCallbacks.delete(t)}listenForCertificatesRequested(t){const e=this.callbackIdCounter++;return this.onCertificateRequestReceivedCallbacks.set(e,t),e}stopListeningForCertificatesRequested(t){this.onCertificateRequestReceivedCallbacks.delete(t)}async initiateHandshake(t){const e=await Qr(this.wallet,void 0,this.originator),i=Date.now(),r=this.certificatesToRequest.certifiers.length>0;this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:e,peerIdentityKey:t,lastUpdate:i,certificatesRequired:r,certificatesValidated:!r});const s={version:is,messageType:"initialRequest",identityKey:await this.getIdentityPublicKey(),initialNonce:e,requestedCertificates:this.certificatesToRequest};return await this.transport.send(s),await this.waitForInitialResponse(e)}async waitForInitialResponse(t){return await new Promise(e=>{const i=this.listenForInitialResponse(t,t=>{this.stopListeningForInitialResponses(i),e(t)})})}listenForInitialResponse(t,e){const i=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(i,{callback:e,sessionNonce:t}),i}stopListeningForInitialResponses(t){this.onInitialResponseReceivedCallbacks.delete(t)}propagateTransportError(t,e){if(e instanceof Error){if(null!=t){const i=e.details;null!=i&&"object"==typeof i?null==i.peerIdentityKey&&(i.peerIdentityKey=t):e.details={peerIdentityKey:t}}throw e}const i=`Failed to send message to peer ${t??"unknown"}: ${String(e)}`;throw new Error(i)}async handleIncomingMessage(t){if("string"!=typeof t.version||t.version!==is)throw new Error(`Invalid or unsupported message auth version! Received: ${t.version}, expected: ${is}`);switch(t.messageType){case"initialRequest":await this.processInitialRequest(t);break;case"initialResponse":await this.processInitialResponse(t);break;case"certificateRequest":await this.processCertificateRequest(t);break;case"certificateResponse":await this.processCertificateResponse(t);break;case"general":await this.processGeneralMessage(t);break;default:throw new Error(`Unknown message type of ${String(t.messageType)} from ${String(t.identityKey)}`)}}async processInitialRequest(t){if("string"!=typeof t.identityKey||"string"!=typeof t.initialNonce||""===t.initialNonce)throw new Error("Missing required fields in initialRequest message.");const e=await Qr(this.wallet,void 0,this.originator),i=Date.now(),r=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0;let s;this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:e,peerNonce:t.initialNonce,peerIdentityKey:t.identityKey,lastUpdate:i,certificatesRequired:r,certificatesValidated:!r}),Array.isArray(t.requestedCertificates?.certifiers)&&t.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach(e=>{e(t.identityKey,t.requestedCertificates)}):s=await ts(this.wallet,t.requestedCertificates,t.identityKey,this.originator));const{signature:n}=await this.wallet.createSignature({data:[...ss.base64ToBytes(t.initialNonce),...ss.base64ToBytes(e)],protocolID:[2,"auth message signature"],keyID:`${t.initialNonce} ${e}`,counterparty:t.identityKey},this.originator),a={version:is,messageType:"initialResponse",identityKey:await this.getIdentityPublicKey(),initialNonce:e,yourNonce:t.initialNonce,certificates:s,requestedCertificates:this.certificatesToRequest,signature:n};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=t.identityKey),await this.transport.send(a)}async processInitialResponse(t){if(!await Zr(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Initial response nonce verification failed from peer: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Peer session not found for peer: ${t.identityKey}`);const i=ss.base64ToBytes((e.sessionNonce??"")+(t.initialNonce??"")),{valid:r}=await this.wallet.verifySignature({data:i,signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${e.sessionNonce??""} ${t.initialNonce??""}`,counterparty:t.identityKey},this.originator);if(!r)throw new Error(`Unable to verify initial response signature for peer: ${t.identityKey}`);if(e.peerNonce=t.initialNonce,e.peerIdentityKey=t.identityKey,e.isAuthenticated=!0,e.certificatesRequired=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0,e.certificatesValidated=!e.certificatesRequired,e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),e.certificatesRequired&&Array.isArray(t.certificates)&&t.certificates.length>0&&(await es(this.wallet,t,this.certificatesToRequest,this.originator),e.certificatesValidated=!0,e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),null!=e.sessionNonce&&this.resolveCertificateValidation(e.sessionNonce),this.onCertificatesReceivedCallbacks.forEach(e=>e(t.identityKey,t.certificates))),this.lastInteractedWithPeer=t.identityKey,this.onInitialResponseReceivedCallbacks.forEach(t=>{t.sessionNonce===e.sessionNonce&&t.callback(e.sessionNonce)}),null!=t.requestedCertificates&&Array.isArray(t.requestedCertificates.certifiers)&&t.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(e=>{e(t.identityKey,t.requestedCertificates)});else{const e=await ts(this.wallet,t.requestedCertificates,t.identityKey,this.originator);e.length>0&&await this.sendCertificateResponse(t.identityKey,e)}}async processCertificateRequest(t){if(!await Zr(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for certificate request message from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{valid:i}=await this.wallet.verifySignature({data:ss.utf8ToBytes(JSON.stringify(t.requestedCertificates)),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:e.peerIdentityKey},this.originator);if(!i)throw new Error(`Invalid signature in certificate request message from ${e.peerIdentityKey}`);if(e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),null!=t.requestedCertificates&&Array.isArray(t.requestedCertificates.certifiers)&&t.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(e=>{e(t.identityKey,t.requestedCertificates)});else{const e=await ts(this.wallet,t.requestedCertificates,t.identityKey,this.originator);await this.sendCertificateResponse(t.identityKey,e)}}async sendCertificateResponse(t,e){const i=await this.getAuthenticatedSession(t),r=Zt(We(32)),{signature:s}=await this.wallet.createSignature({data:ss.utf8ToBytes(JSON.stringify(e)),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),n={version:is,messageType:"certificateResponse",identityKey:await this.getIdentityPublicKey(),nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,certificates:e,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(n)}catch(t){this.propagateTransportError(i.peerIdentityKey,t)}}async processCertificateResponse(t){if(!await Zr(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for certificate response from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{valid:i}=await this.wallet.verifySignature({data:ss.utf8ToBytes(JSON.stringify(t.certificates)),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:t.identityKey},this.originator);if(!i)throw new Error(`Unable to verify certificate response signature for peer: ${t.identityKey}`);Array.isArray(t.certificates)&&t.certificates.length>0&&(await es(this.wallet,t,t.requestedCertificates,this.originator),e.certificatesValidated=!0,e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),null!=e.sessionNonce&&this.resolveCertificateValidation(e.sessionNonce)),this.onCertificatesReceivedCallbacks.forEach(e=>{e(t.identityKey,t.certificates??[])})}async processGeneralMessage(t){if(!await Zr(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for general message from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const i=!0===e.certificatesRequired,r=!0===e.certificatesValidated;if(i&&!r){const t=3e4,i=e.sessionNonce;if(null==i)throw new Error("Session nonce is required for certificate validation");await new Promise((r,s)=>{const n=setTimeout(()=>{null!=this.certificateValidationPromises.get(i)&&(this.certificateValidationPromises.delete(i),s(new Error(`Timeout waiting for certificate validation from peer ${e.peerIdentityKey??"unknown"}`)))},t);"object"==typeof n&&"unref"in n&&n.unref(),this.certificateValidationPromises.set(i,{resolve:()=>{clearTimeout(n),r()},reject:t=>{clearTimeout(n),s(t)}})})}const{valid:s}=await this.wallet.verifySignature({data:t.payload,signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:e.peerIdentityKey},this.originator);if(!s)throw new Error(`Invalid signature in generalMessage from ${e.peerIdentityKey}`);e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),this.lastInteractedWithPeer=t.identityKey,this.onGeneralMessageReceivedCallbacks.forEach(e=>{e(t.identityKey,t.payload??[])})}resolveCertificateValidation(t){const e=this.certificateValidationPromises.get(t);null!=e&&(e.resolve(),this.certificateValidationPromises.delete(t))}async getIdentityPublicKey(){if(null!=this.identityPublicKey)return this.identityPublicKey;const{publicKey:t}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return this.identityPublicKey=t,t}static utf8ToBytes(t){return null!=rs?Array.from(rs.from(t,"utf8")):"undefined"!=typeof TextEncoder?Array.from((new TextEncoder).encode(t)):Wt(t,"utf8")}static base64ToBytes(t){return null!=rs?Array.from(rs.from(t,"base64")):Wt(t,"base64")}}const ns="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch;class as{onDataCallback;fetchClient;baseUrl;constructor(t,e=ns){if("function"!=typeof e)throw new Error("SimplifiedFetchTransport requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=e,this.baseUrl=t}async send(t){if(null==this.onDataCallback)throw new Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==t.messageType)return await new Promise((e,i)=>{(async()=>{try{const i=`${this.baseUrl}/.well-known/auth`,r=(async()=>{try{return await this.fetchClient(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(t){throw this.createNetworkError(i,t)}})();"initialRequest"!==t.messageType&&e();const s=await r;if(!s.ok){const t=Array.from(new Uint8Array(await s.arrayBuffer()));throw this.createUnauthenticatedResponseError(i,s,t)}if(null!=this.onDataCallback){const t=await s.json();this.onDataCallback(t)}"initialRequest"===t.messageType&&e()}catch(t){i(t)}})()});{const e=this.deserializeRequestPayload(t.payload),i=`${this.baseUrl}${e.urlPostfix}`,r=e;if("object"!=typeof e.headers&&(r.headers={}),r.headers["x-bsv-auth-version"]=t.version,r.headers["x-bsv-auth-identity-key"]=t.identityKey,r.headers["x-bsv-auth-nonce"]=t.nonce,r.headers["x-bsv-auth-your-nonce"]=t.yourNonce,r.headers["x-bsv-auth-signature"]=jt(t.signature),r.headers["x-bsv-auth-request-id"]=e.requestId,null!=r.body){const t=r.headers;if(null==t["content-type"])throw new Error("Content-Type header is required for requests with a body.");const e=String(t["content-type"]??"");e.includes("application/json")||e.includes("application/x-www-form-urlencoded")||e.includes("text/plain")?r.body=Yt(r.body):r.body=new Uint8Array(r.body)}let s;try{s=await this.fetchClient(i,{method:r.method,headers:r.headers,body:r.body})}catch(t){throw this.createNetworkError(i,t)}const n=await s.arrayBuffer(),a=Array.from(new Uint8Array(n)),o=["x-bsv-auth-version","x-bsv-auth-identity-key","x-bsv-auth-signature"].filter(t=>{const e=s.headers.get(t);return null==e||0===e.trim().length});if(o.length>0)throw this.createUnauthenticatedResponseError(i,s,a,o);const c=s.headers.get("x-bsv-auth-requested-certificates");let h;if(null!=c)try{h=JSON.parse(c)}catch(t){throw this.createMalformedHeaderError(i,"x-bsv-auth-requested-certificates",c,t)}const u=new se;null!=s.headers.get("x-bsv-auth-request-id")&&u.write(Wt(s.headers.get("x-bsv-auth-request-id"),"base64")),u.writeVarIntNum(s.status);const d=[];s.headers.forEach((t,e)=>{const i=e.toLowerCase();!i.startsWith("x-bsv-")&&"authorization"!==i||i.startsWith("x-bsv-auth")||d.push([i,t])}),d.sort(([t],[e])=>t.localeCompare(e)),u.writeVarIntNum(d.length);for(let t=0;t<d.length;t++){const e=Wt(d[t][0],"utf8");u.writeVarIntNum(e.length),u.write(e);const i=Wt(d[t][1],"utf8");u.writeVarIntNum(i.length),u.write(i)}u.writeVarIntNum(a.length),a.length>0&&u.write(a);const l={version:s.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===s.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:s.headers.get("x-bsv-auth-identity-key"),nonce:s.headers.get("x-bsv-auth-nonce")??void 0,yourNonce:s.headers.get("x-bsv-auth-your-nonce")??void 0,requestedCertificates:h,payload:u.toArray(),signature:Wt(s.headers.get("x-bsv-auth-signature"),"hex")};if(null==l.version)throw this.createUnauthenticatedResponseError(i,s,a);this.onDataCallback(l)}}async onData(t){this.onDataCallback=e=>{t(e).catch(()=>{})}}createNetworkError(t,e){const i=`Network error while sending authenticated request to ${t}`;if(e instanceof Error){const t=new Error(`${i}: ${e.message}`);return t.stack=e.stack,t.cause=e,t}return new Error(`${i}: ${String(e)}`)}createUnauthenticatedResponseError(t,e,i,r=[]){const s=(e.statusText??"").trim(),n=s.length>0?`${e.status} ${s}`:`${e.status}`,a=r.length>0?`missing headers: ${r.join(", ")}`:"response lacked required BSV auth headers",o=this.getBodyPreview(i,e.headers.get("content-type")),c=[`Received HTTP ${n} from ${t} without valid BSV authentication (${a})`];null!=o&&c.push(`body preview: ${o}`);const h=new Error(c.join(" - "));return h.details={url:t,status:e.status,statusText:e.statusText,missingHeaders:r,bodyPreview:o},h}createMalformedHeaderError(t,e,i,r){const s=`Failed to parse ${e} returned by ${t}: ${i}`;if(r instanceof Error){const t=new Error(`${s}. ${r.message}`);return t.stack=r.stack,t.cause=r,t}return new Error(`${s}. ${String(r)}`)}getBodyPreview(t,e){if(0===t.length)return;const i=t.length>1024,r=i?t.slice(0,1024):t;let s;if(this.isTextualContent(e,r))try{s=Yt(r)}catch{s=this.formatBinaryPreview(r,i)}else s=this.formatBinaryPreview(r,i);return s.length>512&&(s=`${s.slice(0,512)}…`),i&&(s=`${s} (truncated)`),s}isTextualContent(t,e){if(0===e.length)return!1;if(null!=t){const e=t.toLowerCase();if(["application/json","application/problem+json","application/xml","application/xhtml+xml","application/javascript","application/ecmascript","application/x-www-form-urlencoded","text/"].some(t=>e.includes(t))||e.includes("charset="))return!0}return e.reduce((t,e)=>9===e||10===e||13===e||e>=32&&e<=126?t+1:t,0)/e.length>.8}formatBinaryPreview(t,e){return`0x${t.map(t=>t.toString(16).padStart(2,"0")).join("")}${e?"…":""}`}deserializeRequestPayload(t){const e=new ne(t),i=Zt(e.read(32)),r=e.readVarIntNum();let s="GET";r>0&&(s=Yt(e.read(r)));const n=e.readVarIntNum();let a="";n>0&&(a=Yt(e.read(n)));const o=e.readVarIntNum();let c="";o>0&&(c=Yt(e.read(o)));const h={},u=e.readVarIntNum();if(u>0)for(let t=0;t<u;t++){const t=e.readVarIntNum(),i=e.read(t),r=Yt(i),s=e.readVarIntNum(),n=e.read(s),a=Yt(n);h[r]=a}let d;const l=e.readVarIntNum();return l>0&&(d=e.read(l)),{urlPostfix:a+c,method:s,headers:h,body:d,requestId:i}}}class os{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(t,e,i,r){this.wallet=t,this.requestedCertificates=e,this.sessionManager=i??new Jr,this.originator=r}async fetch(t,e={}){if("number"==typeof e.retryCounter){if(e.retryCounter<=0)throw new Error("Request failed after maximum number of retries.");e.retryCounter--}const i=await new Promise(async(i,r)=>{try{const{method:s="GET",headers:n={},body:a}=e,o=new URL(t),c=o.origin;let h;if(void 0===this.peers[c]){const t=new as(c);h={peer:new ss(this.wallet,t,this.requestedCertificates,this.sessionManager,void 0,this.originator),pendingCertificateRequests:[]},this.peers[c]=h,this.peers[c].peer.listenForCertificatesReceived((t,e)=>{this.certificatesReceived.push(...e)}),this.peers[c].peer.listenForCertificatesRequested(async(t,e)=>{try{this.peers[c].pendingCertificateRequests.push(!0);const i=await ts(this.wallet,e,t,this.originator);i.length>0&&await this.peers[c].peer.sendCertificateResponse(t,i)}finally{await new Promise(t=>setTimeout(t,500)),this.peers[c].pendingCertificateRequests.shift()}})}else{if(!1===this.peers[c].supportsMutualAuth){try{const r=await this.handleFetchAndValidate(t,e,this.peers[c]);i(r)}catch(t){r(t)}return}h=this.peers[c]}const u=We(32),d=Zt(u),l=await this.serializeRequest(s,n,a,o,u);this.callbacks[d]={resolve:i,reject:r};const f=h.peer.listenForGeneralMessages((t,e)=>{const i=new ne(e);if(Zt(i.read(32))!==d)return;h.peer.stopListeningForGeneralMessages(f),this.peers[c].identityKey=t,this.peers[c].supportsMutualAuth=!0;const r=i.readVarIntNum(),s={},n=i.readVarIntNum();if(n>0)for(let t=0;t<n;t++){const t=i.readVarIntNum(),e=i.read(t),r=Yt(e),n=i.readVarIntNum(),a=i.read(n),o=Yt(a);s[r]=o}let a;s["x-bsv-auth-identity-key"]=t;const o=i.readVarIntNum();o>0&&(a=i.read(o));const u=new Response(a?new Uint8Array(a):null,{status:r,statusText:`${r}`,headers:new Headers(s)});this.callbacks[d].resolve(u),delete this.callbacks[d]});if(h.pendingCertificateRequests.length>0){const t=3e4,e=100;await new Promise((i,r)=>{const s=Date.now(),n=()=>{0!==h.pendingCertificateRequests.length?Date.now()-s>t?r(new Error("Timeout waiting for certificate request to complete")):setTimeout(n,e):i()};n()})}await h.peer.toPeer(l.toArray(),h.identityKey).catch(async s=>{if(s.message.includes("Session not found for nonce")||s.message.includes("without valid BSV authentication")&&null!=h.identityKey&&401===s.details?.status){delete this.peers[c],e.retryCounter??=3;const r=await this.fetch(t,e);return void i(r)}if(s.message.includes("HTTP server failed to authenticate"))try{const r=await this.handleFetchAndValidate(t,e,h);return void i(r)}catch(t){r(t)}else r(s)})}catch(t){r(t)}});return 402===i.status?await this.handlePaymentAndRetry(t,e,i):i}async sendCertificateRequest(t,e){const i=new URL(t).origin;let r;if(void 0!==this.peers[i])r={peer:this.peers[i].peer};else{const t=new as(i);r={peer:new ss(this.wallet,t,this.requestedCertificates,this.sessionManager,this.originator)},this.peers[i]=r}return await new Promise(async(t,s)=>{let n=!1;const a=()=>{n=!0,clearTimeout(c),r.peer.stopListeningForCertificatesReceived(o)},o=r.peer.listenForCertificatesReceived((e,i)=>{n||(a(),this.certificatesReceived.push(...i),t(i))}),c=setTimeout(()=>{n||(a(),s(new Error(`sendCertificateRequest timed out after 30000ms waiting for certificate response from ${i}`)))},3e4);try{await r.peer.requestCertificates(e,r.identityKey)}catch(t){n||(a(),s(t))}})}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(t,e,i,r,s){const n=new se;if(n.write(s),n.writeVarIntNum(t.length),n.write(Wt(t)),r.pathname.length>0){const t=Wt(r.pathname);n.writeVarIntNum(t.length),n.write(t)}else n.writeVarIntNum(-1);if(r.search.length>0){const t=Wt(r.search);n.writeVarIntNum(t.length),n.write(t)}else n.writeVarIntNum(-1);const a=[];for(let[t,i]of Object.entries(e))if(t=t.toLowerCase(),t.startsWith("x-bsv-")||"authorization"===t){if(t.startsWith("x-bsv-auth"))throw new Error("No BSV auth headers allowed here!");a.push([t,i])}else{if(!t.startsWith("content-type"))throw new Error("Unsupported header in the simplified fetch implementation. Only content-type, authorization, and x-bsv-* headers are supported.");i=i.split(";")[0].trim(),a.push([t,i])}a.sort(([t],[e])=>t.localeCompare(e)),n.writeVarIntNum(a.length);for(let t=0;t<a.length;t++){const e=Wt(a[t][0],"utf8");n.writeVarIntNum(e.length),n.write(e);const i=Wt(a[t][1],"utf8");n.writeVarIntNum(i.length),n.write(i)}if(["POST","PUT","PATCH","DELETE"].includes(t.toUpperCase())&&void 0===i){const t=a.find(([t])=>"content-type"===t);i=t&&t[1].includes("application/json")?"{}":""}if(i){const t=await this.normalizeBodyToNumberArray(i);n.writeVarIntNum(t.length),n.write(t)}else n.writeVarIntNum(-1);return n}async handleFetchAndValidate(t,e,i){const r=await fetch(t,e);if(r.headers.forEach(t=>{if(t.toLocaleLowerCase().startsWith("x-bsv"))throw new Error("The server is trying to claim it has been authenticated when it has not!")}),r.ok)return i.supportsMutualAuth=!1,r;throw new Error(`Request failed with status: ${r.status}`)}async handlePaymentAndRetry(t,e={},i){const r=i.headers.get("x-bsv-payment-version");if(!r||"1.0"!==r)throw new Error(`Unsupported x-bsv-payment-version response header. Client version: 1.0, Server version: ${r}`);const s=i.headers.get("x-bsv-payment-satoshis-required");if(!s)throw new Error("Missing x-bsv-payment-satoshis-required response header.");const n=parseInt(s);if(isNaN(n)||n<=0)throw new Error("Invalid x-bsv-payment-satoshis-required response header value.");const a=i.headers.get("x-bsv-auth-identity-key");if("string"!=typeof a)throw new Error("Missing x-bsv-auth-identity-key response header.");const o=i.headers.get("x-bsv-payment-derivation-prefix");if("string"!=typeof o||o.length<1)throw new Error("Missing x-bsv-payment-derivation-prefix response header.");let c=e.paymentContext;if(null!=c?!this.isPaymentContextCompatible(c,n,a,o)&&(this.logPaymentAttempt("warn","Server adjusted payment requirements; regenerating transaction",this.composePaymentLogDetails(t,c)),c=await this.createPaymentContext(t,e,n,a,o)):c=await this.createPaymentContext(t,e,n,a,o),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(t,c,new Error("Maximum payment attempts exceeded before retrying"));const h={...e.headers??{}};h["x-bsv-payment"]=JSON.stringify({derivationPrefix:c.derivationPrefix,derivationSuffix:c.derivationSuffix,transaction:c.transactionBase64});const u={...e,headers:h,paymentContext:c};"number"!=typeof u.retryCounter&&(u.retryCounter=3);const d=c.attempts+1,l=c.maxAttempts;c.attempts=d;const f=this.composePaymentLogDetails(t,c);this.logPaymentAttempt("warn",`Attempting paid request (${d}/${l})`,f);try{const e=await this.fetch(t,u);return this.logPaymentAttempt("info",`Paid request attempt ${d} succeeded`,f),e}catch(e){const r=this.createPaymentErrorEntry(c.attempts,e);if(c.errors.push(r),this.logPaymentAttempt("error",`Paid request attempt ${d} failed`,{...f,error:{message:r.message,stack:r.stack}}),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(t,c,e);const s=this.getPaymentRetryDelay(c.attempts);return await this.wait(s),this.handlePaymentAndRetry(t,u,i)}}isPaymentContextCompatible(t,e,i,r){return t.satoshisRequired===e&&t.serverIdentityKey===i&&t.derivationPrefix===r}async createPaymentContext(t,e,i,r,s){const n=await Qr(this.wallet,void 0,this.originator),{publicKey:a}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${s} ${n}`,counterparty:r},this.originator),o=(new Fi).lock($e.fromString(a).toAddress()).toHex(),{tx:c}=await this.wallet.createAction({description:`Payment for request to ${new URL(t).origin}`,outputs:[{satoshis:i,lockingScript:o,customInstructions:JSON.stringify({derivationPrefix:s,derivationSuffix:n,payee:r}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}},this.originator),{publicKey:h}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return{satoshisRequired:i,transactionBase64:Zt(c),derivationPrefix:s,derivationSuffix:n,serverIdentityKey:r,clientIdentityKey:h,attempts:0,maxAttempts:this.getMaxPaymentAttempts(e),errors:[],requestSummary:this.buildPaymentRequestSummary(t,e)}}getMaxPaymentAttempts(t){const e="number"==typeof t.paymentRetryAttempts?t.paymentRetryAttempts:void 0;return"number"==typeof e&&e>0?Math.floor(e):3}buildPaymentRequestSummary(t,e){const i={...e.headers??{}},r="string"==typeof e.method?e.method.toUpperCase():"GET",s=this.describeRequestBodyForLogging(e.body);return{url:t,method:r,headers:i,bodyType:s.type,bodyByteLength:s.byteLength}}describeRequestBodyForLogging(t){if(null==t)return{type:"none",byteLength:0};if("string"==typeof t)return{type:"string",byteLength:Wt(t,"utf8").length};if(Array.isArray(t))return t.every(t=>"number"==typeof t)?{type:"number[]",byteLength:t.length}:{type:"array",byteLength:t.length};if("undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer)return{type:"ArrayBuffer",byteLength:t.byteLength};if("undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(t))return{type:null!=t.constructor?t.constructor.name:"TypedArray",byteLength:t.byteLength};if("undefined"!=typeof Blob&&t instanceof Blob)return{type:"Blob",byteLength:t.size};if("undefined"!=typeof FormData&&t instanceof FormData)return{type:"FormData",byteLength:0};if("undefined"!=typeof URLSearchParams&&t instanceof URLSearchParams){const e=t.toString();return{type:"URLSearchParams",byteLength:Wt(e,"utf8").length}}if("undefined"!=typeof ReadableStream&&t instanceof ReadableStream)return{type:"ReadableStream",byteLength:0};try{const e=JSON.stringify(t);if("string"==typeof e)return{type:"object",byteLength:Wt(e,"utf8").length}}catch(t){}return{type:typeof t,byteLength:0}}composePaymentLogDetails(t,e){return{url:t,request:e.requestSummary,payment:{satoshis:e.satoshisRequired,transactionBase64:e.transactionBase64,derivationPrefix:e.derivationPrefix,derivationSuffix:e.derivationSuffix,serverIdentityKey:e.serverIdentityKey,clientIdentityKey:e.clientIdentityKey},attempts:{used:e.attempts,max:e.maxAttempts},errors:e.errors}}logPaymentAttempt(t,e,i){const r="[AuthFetch][Payment]";"error"===t?console.error(`${r} ${e}`,i):"warn"===t?console.warn(`${r} ${e}`,i):"function"==typeof console.info?console.info(`${r} ${e}`,i):console.log(`${r} ${e}`,i)}createPaymentErrorEntry(t,e){const i={attempt:t,timestamp:(new Date).toISOString(),message:"",stack:void 0};return e instanceof Error?(i.message=e.message,i.stack=e.stack??void 0):i.message=String(e),i}getPaymentRetryDelay(t){return 250*Math.min(t,5)}async wait(t){t<=0||await new Promise(e=>setTimeout(e,t))}buildPaymentFailureError(t,e,i){const r=`Paid request to ${t} failed after ${e.attempts}/${e.maxAttempts} attempts. Sent ${e.satoshisRequired} satoshis to ${e.serverIdentityKey}.`,s=new Error(r),n={request:e.requestSummary,payment:{satoshis:e.satoshisRequired,transactionBase64:e.transactionBase64,derivationPrefix:e.derivationPrefix,derivationSuffix:e.derivationSuffix,serverIdentityKey:e.serverIdentityKey,clientIdentityKey:e.clientIdentityKey},attempts:{used:e.attempts,max:e.maxAttempts},errors:e.errors};return s.details=n,i instanceof Error&&(s.cause=i),s}async normalizeBodyToNumberArray(t){if(null==t)return[];if("object"==typeof t)return Wt(JSON.stringify(t,"utf8"));if(Array.isArray(t)&&t.every(t=>"number"==typeof t))return t;if("string"==typeof t)return Wt(t,"utf8");if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)){const e=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer);return Array.from(e)}if(t instanceof Blob){const e=await t.arrayBuffer();return Array.from(new Uint8Array(e))}if(t instanceof FormData){const e=[];t.forEach((t,i)=>{e.push([i,t.toString()])});const i=new URLSearchParams(e).toString();return Wt(i,"utf8")}if(t instanceof URLSearchParams)return Wt(t.toString(),"utf8");if(t instanceof ReadableStream)throw new Error("ReadableStream cannot be directly converted to number[].");throw new Error("Unsupported body type in this SimplifiedFetch implementation.")}}class cs{pushDrop;static decode(t){const e=Di.decode(t);if(e.fields.length<4)throw new Error("Invalid SHIP/SLAP advertisement!");const i=Yt(e.fields[0]);if("SHIP"!==i&&"SLAP"!==i)throw new Error("Invalid protocol type!");return{protocol:i,identityKey:jt(e.fields[1]),domain:Yt(e.fields[2]),topicOrService:Yt(e.fields[3])}}constructor(t,e){this.pushDrop=new Di(t,e)}async lock(t,e,i){const{publicKey:r}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([Wt(t,"utf8"),Wt(r,"hex"),Wt(e,"utf8"),Wt(i,"utf8")],[2,"SHIP"===t?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}unlock(t){return this.pushDrop.unlock([2,"SHIP"===t?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}}const hs="bsvsdk_overlay_host_reputation_v1";class us{stats;store;constructor(t){this.stats=new Map,this.store=t??this.getLocalStorageAdapter(),this.loadFromStorage()}reset(){this.stats.clear()}recordSuccess(t,e){const i=this.getOrCreate(t),r=Date.now(),s=Number.isFinite(e)&&e>=0?e:1500;null===i.avgLatencyMs?i.avgLatencyMs=s:i.avgLatencyMs=.75*i.avgLatencyMs+.25*s,i.lastLatencyMs=s,i.totalSuccesses+=1,i.consecutiveFailures=0,i.backoffUntil=0,i.lastUpdatedAt=r,i.lastError=void 0,this.saveToStorage()}recordFailure(t,e){const i=this.getOrCreate(t),r=Date.now();i.totalFailures+=1,i.consecutiveFailures+=1;const s="string"==typeof e?e:e instanceof Error?e.message:void 0;"string"==typeof s&&(s.includes("ERR_NAME_NOT_RESOLVED")||s.includes("ENOTFOUND")||s.includes("getaddrinfo")||s.includes("Failed to fetch"))&&i.consecutiveFailures<3&&(i.consecutiveFailures=3);const n=Math.max(i.consecutiveFailures-2,0);if(0===n)i.backoffUntil=0;else{const t=Math.min(6e4,1e3*Math.pow(2,n-1));i.backoffUntil=r+t}i.lastUpdatedAt=r,i.lastError="string"==typeof e?e:e instanceof Error?e.message:void 0,this.saveToStorage()}rankHosts(t,e=Date.now()){const i=new Map;t.forEach((t,e)=>{"string"==typeof t&&0!==t.length&&(i.has(t)||i.set(t,e))});const r=Array.from(i.keys()).map(t=>{const r=this.getOrCreate(t);return{...r,score:this.computeScore(r,e),originalOrder:i.get(t)??0}});return r.sort((t,i)=>{const r=t.backoffUntil>e;return r!==i.backoffUntil>e?r?1:-1:t.score!==i.score?t.score-i.score:t.totalSuccesses!==i.totalSuccesses?i.totalSuccesses-t.totalSuccesses:t.originalOrder-i.originalOrder}),r.map(({originalOrder:t,...e})=>e)}snapshot(t){const e=this.stats.get(t);return null!=e?{...e}:void 0}getStorage(){try{const t="object"==typeof globalThis?globalThis:void 0;if(null==t||null==t.localStorage)return;return t.localStorage}catch{return}}getLocalStorageAdapter(){const t=this.getStorage();if(null!=t)return{get:e=>{try{return t.getItem(e)}catch{return null}},set:(e,i)=>{try{t.setItem(e,i)}catch{}}}}loadFromStorage(){const t=this.store;if(null!=t)try{const e=t.get(hs);if("string"!=typeof e||0===e.length)return;const i=JSON.parse(e);if("object"!=typeof i||null===i)return;this.stats.clear();for(const t of Object.keys(i)){const e=i[t];if(null!=e&&"object"==typeof e){const i={host:String(e.host??t),totalSuccesses:Number(e.totalSuccesses??0),totalFailures:Number(e.totalFailures??0),consecutiveFailures:Number(e.consecutiveFailures??0),avgLatencyMs:null==e.avgLatencyMs?null:Number(e.avgLatencyMs),lastLatencyMs:null==e.lastLatencyMs?null:Number(e.lastLatencyMs),backoffUntil:Number(e.backoffUntil??0),lastUpdatedAt:Number(e.lastUpdatedAt??0),lastError:"string"==typeof e.lastError?e.lastError:void 0};this.stats.set(i.host,i)}}}catch{}}saveToStorage(){const t=this.store;if(null!=t)try{const e={};for(const[t,i]of this.stats.entries())e[t]=i;t.set(hs,JSON.stringify(e))}catch{}}computeScore(t,e){const i=t.avgLatencyMs??1500,r=400*t.consecutiveFailures,s=Math.min(30*t.totalSuccesses,i/2);return i+r+(t.backoffUntil>e?t.backoffUntil-e:0)-s}getOrCreate(t){let e=this.stats.get(t);return null==e&&(e={host:t,totalSuccesses:0,totalFailures:0,consecutiveFailures:0,avgLatencyMs:null,lastLatencyMs:null,backoffUntil:0,lastUpdatedAt:0},this.stats.set(t,e)),e}}const ds=new us,ls="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch,fs=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],ps=["https://testnet-users.bapp.dev"];class gs{fetchClient;allowHTTP;constructor(t=ls,e=!1){if("function"!=typeof t)throw new Error("HTTPSOverlayLookupFacilitator requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=t,this.allowHTTP=e}async lookup(t,e,i=5e3){if(!t.startsWith("https:")&&!this.allowHTTP)throw new Error('HTTPS facilitator can only use URLs that start with "https:"');const r="undefined"!=typeof AbortController?new AbortController:void 0,s=setTimeout(()=>{try{r?.abort()}catch{}},i);try{const i={method:"POST",headers:{"Content-Type":"application/json","X-Aggregation":"yes"},body:JSON.stringify({service:e.service,query:e.query}),signal:r?.signal},s=await this.fetchClient(`${t}/lookup`,i);if(!s.ok)throw new Error(`Failed to facilitate lookup (HTTP ${s.status})`);if("application/octet-stream"===s.headers.get("content-type")){const t=await s.arrayBuffer(),e=new ne([...new Uint8Array(t)]),i=e.readVarIntNum(),r=[];for(let t=0;t<i;t++){const t=jt(e.read(32)),i=e.readVarIntNum(),s=e.readVarIntNum();let n;s>0&&(n=e.read(s)),r.push({txid:t,outputIndex:i,context:n})}const n=e.read();return{type:"output-list",outputs:r.map(t=>({outputIndex:t.outputIndex,context:t.context,beef:ir.fromBEEF(n,t.txid).toBEEF()}))}}return await s.json()}catch(t){if("AbortError"===t?.name)throw new Error("Request timed out");throw t}finally{clearTimeout(s)}}}class ys{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostReputation;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(t={}){this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new gs(void 0,"local"===this.networkPreset),this.slapTrackers=t.slapTrackers??("mainnet"===this.networkPreset?fs:ps);const e=t.hostOverrides??{};this.assertValidOverrideServices(e),this.hostOverrides=e,this.additionalHosts=t.additionalHosts??{};const i=t.reputationStorage;"localStorage"===i?this.hostReputation=new us:"object"==typeof i&&null!==i&&"function"==typeof i.get&&"function"==typeof i.set?this.hostReputation=new us(i):this.hostReputation=ds,this.hostsTtlMs=t.cache?.hostsTtlMs??3e5,this.hostsMaxEntries=t.cache?.hostsMaxEntries??128,this.txMemoTtlMs=t.cache?.txMemoTtlMs??6e5,this.hostsCache=new Map,this.hostsInFlight=new Map,this.txMemo=new Map}async query(t,e){let i=[];if(i="ls_slap"===t.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[t.service]?this.hostOverrides[t.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.getCompetentHostsCached(t.service),this.additionalHosts[t.service]?.length>0){const e=this.additionalHosts[t.service],r=new Set(i);for(const t of e)r.has(t)||i.push(t)}if(i.length<1)throw new Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${t.service}`);const r=this.prepareHostsForQuery(i,`lookup service ${t.service}`);if(r.length<1)throw new Error(`All competent hosts for ${t.service} are temporarily unavailable due to backoff.`);const s=await new Promise(i=>{const s=[];let n=r.length,a=null;const o=()=>{null!==a&&clearTimeout(a),i(s)};for(const i of r)this.lookupHostWithTracking(i,t,e).then(t=>{"output-list"===t?.type&&Array.isArray(t.outputs)&&t.outputs.length>0&&(s.push(t),1===s.length&&n>1&&(a=setTimeout(o,200)))}).catch(()=>{}).finally(()=>{n--,0===n&&o()})}),n=new Map,a=t=>"object"!=typeof t?"":t.join(",");for(const t of s)for(const e of t.outputs){const t=a(e.beef);let i=this.txMemo.get(t);const r=Date.now();if("object"!=typeof i||null===i||i.expiresAt<=r)try{i={txId:ir.fromBEEF(e.beef).id("hex"),expiresAt:r+this.txMemoTtlMs},this.txMemo.size>4096&&this.evictOldest(this.txMemo),this.txMemo.set(t,i)}catch{continue}const s=`${i.txId}.${e.outputIndex}`;n.set(s,e)}return{type:"output-list",outputs:Array.from(n.values())}}async getCompetentHostsCached(t){const e=Date.now(),i=this.hostsCache.get(t);if("object"==typeof i&&i.expiresAt>e)return i.hosts.slice();if("object"==typeof i&&i.expiresAt<=e)return this.hostsInFlight.has(t)||this.hostsInFlight.set(t,this.refreshHosts(t).finally(()=>{this.hostsInFlight.delete(t)})),i.hosts.slice();if(this.hostsInFlight.has(t))try{const e=await this.hostsInFlight.get(t);if("object"!=typeof e)throw new Error("Hosts is not defined.");return e.slice()}catch{}const r=this.refreshHosts(t).finally(()=>{this.hostsInFlight.delete(t)});return this.hostsInFlight.set(t,r),(await r).slice()}async refreshHosts(t){const e=await this.findCompetentHosts(t),i=Date.now()+this.hostsTtlMs;if(!this.hostsCache.has(t)&&this.hostsCache.size>=this.hostsMaxEntries){const t=this.hostsCache.keys().next().value;void 0!==t&&this.hostsCache.delete(t)}return this.hostsCache.set(t,{hosts:e,expiresAt:i}),e}extractHostsFromAnswer(t,e){const i=[];if("output-list"!==t.type)return i;for(const r of t.outputs)try{const t=ir.fromBEEF(r.beef),s=t.outputs[r.outputIndex]?.lockingScript;if("object"!=typeof s||null===s)continue;const n=cs.decode(s);if(n.topicOrService!==e||"SLAP"!==n.protocol)continue;"string"==typeof n.domain&&n.domain.length>0&&i.push(n.domain)}catch{continue}return i}async findCompetentHosts(t){const e={service:"ls_slap",query:{service:t}},i=this.prepareHostsForQuery(this.slapTrackers,"SLAP trackers");return 0===i.length?[]:await new Promise(r=>{const s=new Set;let n=!1,a=i.length;for(const o of i)this.lookupHostWithTracking(o,e,5e3).then(e=>{const i=this.extractHostsFromAnswer(e,t);for(const t of i)s.add(t);!n&&s.size>0&&(n=!0,r([...s]))}).catch(()=>{}).finally(()=>{a--,0!==a||n||(n=!0,r([...s]))})})}evictOldest(t){const e=t.keys().next().value;void 0!==e&&t.delete(e)}assertValidOverrideServices(t){for(const e of Object.keys(t))if(!e.startsWith("ls_"))throw new Error(`Host override service names must start with "ls_": ${e}`)}prepareHostsForQuery(t,e){if(0===t.length)return[];const i=Date.now(),r=this.hostReputation.rankHosts(t,i),s=r.filter(t=>t.backoffUntil<=i).map(t=>t.host);if(s.length>0)return s;const n=Math.min(...r.map(t=>t.backoffUntil)),a=Math.max(n-i,0);throw new Error(`All ${e} hosts are backing off for approximately ${a}ms due to repeated failures.`)}async lookupHostWithTracking(t,e,i){const r=Date.now();try{const s=await this.facilitator.lookup(t,e,i),n=Date.now()-r;return"object"==typeof s&&null!==s&&"output-list"===s.type&&Array.isArray(s.outputs)?this.hostReputation.recordSuccess(t,n):this.hostReputation.recordFailure(t,"Invalid lookup response"),s}catch(e){throw this.hostReputation.recordFailure(t,e),e}}}class bs{httpClient;allowHTTP;constructor(t=fetch,e=!1){this.httpClient=t,this.allowHTTP=e}async send(t,e){if(!t.startsWith("https:")&&!this.allowHTTP)throw new Error('HTTPS facilitator can only use URLs that start with "https:"');const i={"Content-Type":"application/octet-stream","X-Topics":JSON.stringify(e.topics)};let r;if(Array.isArray(e.offChainValues)){i["x-includes-off-chain-values"]="true";const t=new se;t.writeVarIntNum(e.beef.length),t.write(e.beef),t.write(e.offChainValues),r=new Uint8Array(t.toArray())}else r=new Uint8Array(e.beef);const s=await fetch(`${t}/submit`,{method:"POST",headers:i,body:r});if(s.ok)return await s.json();throw new Error("Failed to facilitate broadcast")}}class ms{topics;facilitator;resolver;requireAcknowledgmentFromAllHostsForTopics;requireAcknowledgmentFromAnyHostForTopics;requireAcknowledgmentFromSpecificHostsForTopics;networkPreset;interestedHostsCache=null;interestedHostsInFlight=null;interestedHostsTtlMs;constructor(t,e={}){if(0===t.length)throw new Error("At least one topic is required for broadcast.");if(t.some(t=>!t.startsWith("tm_")))throw new Error('Every topic must start with "tm_".');this.topics=t,this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new bs(void 0,"local"===this.networkPreset),this.resolver=e.resolver??new ys({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=e.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=e.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=e.requireAcknowledgmentFromSpecificHostsForTopics??{},this.interestedHostsTtlMs=3e5}async broadcast(t){let e;const i=t.metadata.get("OffChainValues");try{e=t.toBEEF()}catch(t){throw new Error("Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.")}const r=await this.findInterestedHosts();if(0===Object.keys(r).length)return{status:"error",code:"ERR_NO_HOSTS_INTERESTED",description:`No ${this.networkPreset} hosts are interested in receiving this transaction.`};const s=Object.entries(r).map(async([t,r])=>{try{const s=await this.facilitator.send(t,{beef:e,offChainValues:i,topics:[...r]});if(null==s||0===Object.keys(s).length)throw new Error("Steak has no topics.");return{host:t,success:!0,steak:s}}catch(e){return console.error(e),{host:t,success:!1,error:e}}}),n=(await Promise.all(s)).filter(t=>t.success);if(0===n.length)return{status:"error",code:"ERR_ALL_HOSTS_REJECTED",description:`All ${this.networkPreset} topical hosts have rejected the transaction.`};const a={};for(const t of n){const e=t.host,i=t.steak,r=new Set;for(const[t,e]of Object.entries(i)){const i=e.outputsToAdmit,s=e.coinsToRetain,n=e.coinsRemoved;(i?.length>0||s?.length>0||n?.length>0)&&r.add(t)}a[e]=r}let o,c,h,u;return"all"===this.requireAcknowledgmentFromAllHostsForTopics?(o=this.topics,c="all"):"any"===this.requireAcknowledgmentFromAllHostsForTopics?(o=this.topics,c="any"):Array.isArray(this.requireAcknowledgmentFromAllHostsForTopics)?(o=this.requireAcknowledgmentFromAllHostsForTopics,c="all"):(o=this.topics,c="all"),o.length>0&&!this.checkAcknowledgmentFromAllHosts(a,o,c)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED",description:"Not all hosts acknowledged the required topics."}:("all"===this.requireAcknowledgmentFromAnyHostForTopics?(h=this.topics,u="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(h=this.topics,u="any"):Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?(h=this.requireAcknowledgmentFromAnyHostForTopics,u="all"):(h=[],u="all"),h.length>0&&!this.checkAcknowledgmentFromAnyHost(a,h,u)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ANY_HOST_FAILED",description:"No host acknowledged the required topics."}:Object.keys(this.requireAcknowledgmentFromSpecificHostsForTopics).length>0&&!this.checkAcknowledgmentFromSpecificHosts(a,this.requireAcknowledgmentFromSpecificHostsForTopics)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_SPECIFIC_HOSTS_FAILED",description:"Specific hosts did not acknowledge the required topics."}:{status:"success",txid:t.id("hex"),message:`Sent to ${n.length} Overlay Services ${1===n.length?"host":"hosts"}.`})}checkAcknowledgmentFromAllHosts(t,e,i){for(const r of Object.values(t))if("all"===i){for(const t of e)if(!r.has(t))return!1}else if("any"===i){let t=!1;for(const i of e)if(r.has(i)){t=!0;break}if(!t)return!1}return!0}checkAcknowledgmentFromAnyHost(t,e,i){if("all"===i){for(const i of Object.values(t)){let t=!0;for(const r of e)if(!i.has(r)){t=!1;break}if(t)return!0}return!1}for(const i of Object.values(t))for(const t of e)if(i.has(t))return!0;return!1}checkAcknowledgmentFromSpecificHosts(t,e){for(const[i,r]of Object.entries(e)){const e=t[i];if(null==e)return!1;let s,n;if("all"===r||"any"===r)n=r,s=this.topics;else{if(!Array.isArray(r))continue;s=r,n="all"}if("all"===n){for(const t of s)if(!e.has(t))return!1}else if("any"===n){let t=!1;for(const i of s)if(e.has(i)){t=!0;break}if(!t)return!1}}return!0}async findInterestedHosts(){if("local"===this.networkPreset){const t=new Set;for(let e=0;e<this.topics.length;e++)t.add(this.topics[e]);return{"http://localhost:8080":t}}const t=Date.now();if(null!=this.interestedHostsCache&&this.interestedHostsCache.expiresAt>t)return this.interestedHostsCache.hosts;if(null!=this.interestedHostsInFlight)return await this.interestedHostsInFlight;this.interestedHostsInFlight=this.fetchInterestedHosts();try{const t=await this.interestedHostsInFlight;return this.interestedHostsCache={hosts:t,expiresAt:Date.now()+this.interestedHostsTtlMs},t}finally{this.interestedHostsInFlight=null}}async fetchInterestedHosts(){const t={},e=await this.resolver.query({service:"ls_ship",query:{topics:this.topics}},5e3);if("output-list"!==e.type)throw new Error("SHIP answer is not an output list.");for(const i of e.outputs)try{const e=ir.fromBEEF(i.beef).outputs[i.outputIndex].lockingScript,r=cs.decode(e);if(!this.topics.includes(r.topicOrService)||"SHIP"!==r.protocol)continue;void 0===t[r.domain]&&(t[r.domain]=new Set),t[r.domain].add(r.topicOrService)}catch(t){continue}return t}}const ws=Object.create(null);ws.open="0",ws.close="1",ws.ping="2",ws.pong="3",ws.message="4",ws.upgrade="5",ws.noop="6";const vs=Object.create(null);Object.keys(ws).forEach(t=>{vs[ws[t]]=t});const Is={type:"error",data:"parser error"},ks="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Ss="function"==typeof ArrayBuffer,Es=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,xs=({type:t,data:e},i,r)=>ks&&e instanceof Blob?i?r(e):Ps(e,r):Ss&&(e instanceof ArrayBuffer||Es(e))?i?r(e):Ps(new Blob([e]),r):r(ws[t]+(e||"")),Ps=(t,e)=>{const i=new FileReader;return i.onload=function(){const t=i.result.split(",")[1];e("b"+(t||""))},i.readAsDataURL(t)};function _s(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let As;const Ns="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)Ns["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const Os="function"==typeof ArrayBuffer,Ts=(t,e)=>{if("string"!=typeof t)return{type:"message",data:Rs(t,e)};const i=t.charAt(0);return"b"===i?{type:"message",data:Cs(t.substring(1),e)}:vs[i]?t.length>1?{type:vs[i],data:t.substring(1)}:{type:vs[i]}:Is},Cs=(t,e)=>{if(Os){const i=(t=>{let e,i,r,s,n,a=.75*t.length,o=t.length,c=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);const h=new ArrayBuffer(a),u=new Uint8Array(h);for(e=0;e<o;e+=4)i=Ns[t.charCodeAt(e)],r=Ns[t.charCodeAt(e+1)],s=Ns[t.charCodeAt(e+2)],n=Ns[t.charCodeAt(e+3)],u[c++]=i<<2|r>>4,u[c++]=(15&r)<<4|s>>2,u[c++]=(3&s)<<6|63&n;return h})(t);return Rs(i,e)}return{base64:!0,data:t}},Rs=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,Bs=String.fromCharCode(30);let Ls;function Ms(t){return t.reduce((t,e)=>t+e.length,0)}function Fs(t,e){if(t[0].length===e)return t.shift();const i=new Uint8Array(e);let r=0;for(let s=0;s<e;s++)i[s]=t[0][r++],r===t[0].length&&(t.shift(),r=0);return t.length&&r<t[0].length&&(t[0]=t[0].slice(r)),i}function Us(t){if(t)return function(t){for(var e in Us.prototype)t[e]=Us.prototype[e];return t}(t)}Us.prototype.on=Us.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Us.prototype.once=function(t,e){function i(){this.off(t,i),e.apply(this,arguments)}return i.fn=e,this.on(t,i),this},Us.prototype.off=Us.prototype.removeListener=Us.prototype.removeAllListeners=Us.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var i,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var s=0;s<r.length;s++)if((i=r[s])===e||i.fn===e){r.splice(s,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},Us.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),i=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(i){r=0;for(var s=(i=i.slice(0)).length;r<s;++r)i[r].apply(this,e)}return this},Us.prototype.emitReserved=Us.prototype.emit,Us.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Us.prototype.hasListeners=function(t){return!!this.listeners(t).length};const Ds="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),Hs="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function qs(t,...e){return e.reduce((e,i)=>(t.hasOwnProperty(i)&&(e[i]=t[i]),e),{})}const Vs=Hs.setTimeout,Ks=Hs.clearTimeout;function $s(t,e){e.useNativeTimers?(t.setTimeoutFn=Vs.bind(Hs),t.clearTimeoutFn=Ks.bind(Hs)):(t.setTimeoutFn=Hs.setTimeout.bind(Hs),t.clearTimeoutFn=Hs.clearTimeout.bind(Hs))}function js(t){return"string"==typeof t?function(t){let e=0,i=0;for(let r=0,s=t.length;r<s;r++)e=t.charCodeAt(r),e<128?i+=1:e<2048?i+=2:e<55296||e>=57344?i+=3:(r++,i+=4);return i}(t):Math.ceil(1.33*(t.byteLength||t.size))}function zs(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Ws extends Error{constructor(t,e,i){super(t),this.description=e,this.context=i,this.type="TransportError"}}class Gs extends Us{constructor(t){super(),this.writable=!1,$s(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,i){return super.emitReserved("error",new Ws(t,e,i)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=Ts(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=function(t){let e="";for(let i in t)t.hasOwnProperty(i)&&(e.length&&(e+="&"),e+=encodeURIComponent(i)+"="+encodeURIComponent(t[i]));return e}(t);return e.length?"?"+e:""}}class Xs extends Gs{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const i=t.split(Bs),r=[];for(let t=0;t<i.length;t++){const s=Ts(i[t],e);if(r.push(s),"error"===s.type)break}return r})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const i=t.length,r=new Array(i);let s=0;t.forEach((t,n)=>{xs(t,!1,t=>{r[n]=t,++s===i&&e(r.join(Bs))})})})(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=zs()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let Ys=!1;try{Ys="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const Js=Ys;function Zs(){}class Qs extends Xs{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let i=location.port;i||(i=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||i!==t.port}}doWrite(t,e){const i=this.request({method:"POST",data:t});i.on("success",e),i.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class tn extends Us{constructor(t,e,i){super(),this.createRequest=t,$s(this,i),this._opts=i,this._method=i.method||"GET",this._uri=e,this._data=void 0!==i.data?i.data:null,this._create()}_create(){var t;const e=qs(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const i=this._xhr=this.createRequest(e);try{i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&i.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{i.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var t;3===i.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(i.getResponseHeader("set-cookie"))),4===i.readyState&&(200===i.status||1223===i.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof i.status?i.status:0)},0))},i.send(this._data)}catch(t){return void this.setTimeoutFn(()=>{this._onError(t)},0)}"undefined"!=typeof document&&(this._index=tn.requestsCount++,tn.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=Zs,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete tn.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}function en(){for(let t in tn.requests)tn.requests.hasOwnProperty(t)&&tn.requests[t].abort()}tn.requestsCount=0,tn.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",en):"function"==typeof addEventListener&&addEventListener("onpagehide"in Hs?"pagehide":"unload",en,!1));const rn=function(){const t=sn({xdomain:!1});return t&&null!==t.responseType}();function sn(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||Js))return new XMLHttpRequest}catch(t){}if(!e)try{return new(Hs[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const nn="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class an extends Gs{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,i=nn?{}:qs(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,i)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const i=t[e],r=e===t.length-1;xs(i,this.supportsBinary,t=>{try{this.doWrite(i,t)}catch(t){}r&&Ds(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=zs()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const on=Hs.WebSocket||Hs.MozWebSocket,cn={websocket:class extends an{createSocket(t,e,i){return nn?new on(t,e,i):e?new on(t,e):new on(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends Gs{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=function(t,e){Ls||(Ls=new TextDecoder);const i=[];let r=0,s=-1,n=!1;return new TransformStream({transform(a,o){for(i.push(a);;){if(0===r){if(Ms(i)<1)break;const t=Fs(i,1);n=!(128&~t[0]),s=127&t[0],r=s<126?3:126===s?1:2}else if(1===r){if(Ms(i)<2)break;const t=Fs(i,2);s=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),r=3}else if(2===r){if(Ms(i)<8)break;const t=Fs(i,8),e=new DataView(t.buffer,t.byteOffset,t.length),n=e.getUint32(0);if(n>Math.pow(2,21)-1){o.enqueue(Is);break}s=n*Math.pow(2,32)+e.getUint32(4),r=3}else{if(Ms(i)<s)break;const t=Fs(i,s);o.enqueue(Ts(n?t:Ls.decode(t),e)),r=0}if(0===s||s>t){o.enqueue(Is);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=t.readable.pipeThrough(e).getReader(),r=new TransformStream({transform(t,e){!function(t,e){ks&&t.data instanceof Blob?t.data.arrayBuffer().then(_s).then(e):Ss&&(t.data instanceof ArrayBuffer||Es(t.data))?e(_s(t.data)):xs(t,!1,t=>{As||(As=new TextEncoder),e(As.encode(t))})}(t,i=>{const r=i.length;let s;if(r<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,r);else if(r<65536){s=new Uint8Array(3);const t=new DataView(s.buffer);t.setUint8(0,126),t.setUint16(1,r)}else{s=new Uint8Array(9);const t=new DataView(s.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(r))}t.data&&"string"!=typeof t.data&&(s[0]|=128),e.enqueue(s),e.enqueue(i)})}});r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const s=()=>{i.read().then(({done:t,value:e})=>{t||(this.onPacket(e),s())}).catch(t=>{})};s();const n={type:"open"};this.query.sid&&(n.data=`{"sid":"${this.query.sid}"}`),this._writer.write(n).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const i=t[e],r=e===t.length-1;this._writer.write(i).then(()=>{r&&Ds(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends Qs{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=rn&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new tn(sn,this.uri(),t)}}},hn=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,un=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function dn(t){if(t.length>8e3)throw"URI too long";const e=t,i=t.indexOf("["),r=t.indexOf("]");-1!=i&&-1!=r&&(t=t.substring(0,i)+t.substring(i,r).replace(/:/g,";")+t.substring(r,t.length));let s=hn.exec(t||""),n={},a=14;for(;a--;)n[un[a]]=s[a]||"";return-1!=i&&-1!=r&&(n.source=e,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=function(t,e){const i=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||i.splice(0,1),"/"==e.slice(-1)&&i.splice(i.length-1,1),i}(0,n.path),n.queryKey=function(t,e){const i={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,r){e&&(i[e]=r)}),i}(0,n.query),n}const ln="function"==typeof addEventListener&&"function"==typeof removeEventListener,fn=[];ln&&addEventListener("offline",()=>{fn.forEach(t=>t())},!1);class pn extends Us{constructor(t,e){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const i=dn(t);e.hostname=i.host,e.secure="https"===i.protocol||"wss"===i.protocol,e.port=i.port,i.query&&(e.query=i.query)}else e.host&&(e.hostname=dn(e.host).host);$s(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(t=>{const e=t.prototype.name;this.transports.push(e),this._transportsByName[e]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},i=t.split("&");for(let t=0,r=i.length;t<r;t++){let r=i[t].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}(this.opts.query)),ln&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},fn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const i=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](i)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&pn.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",pn.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e<this.writeBuffer.length;e++){const i=this.writeBuffer[e].data;if(i&&(t+=js(i)),e>0&&t>this._maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Ds(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,i){return this._sendPacket("message",t,e,i),this}send(t,e,i){return this._sendPacket("message",t,e,i),this}_sendPacket(t,e,i,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof i&&(r=i,i=null),"closing"===this.readyState||"closed"===this.readyState)return;(i=i||{}).compress=!1!==i.compress;const s={type:t,data:e,options:i};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},i=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?i():t()}):this.upgrading?i():t()),this}_onError(t){if(pn.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ln&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=fn.indexOf(this._offlineEventListener);-1!==t&&fn.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}pn.protocol=4;class gn extends pn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),i=!1;pn.priorWebsocketSuccess=!1;const r=()=>{i||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!i)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;pn.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{i||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function s(){i||(i=!0,h(),e.close(),e=null)}const n=t=>{const i=new Error("probe error: "+t);i.transport=e.name,s(),this.emitReserved("upgradeError",i)};function a(){n("transport closed")}function o(){n("socket closed")}function c(t){e&&t.name!==e.name&&s()}const h=()=>{e.removeListener("open",r),e.removeListener("error",n),e.removeListener("close",a),this.off("close",o),this.off("upgrading",c)};e.once("open",r),e.once("error",n),e.once("close",a),this.once("close",o),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{i||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let i=0;i<t.length;i++)~this.transports.indexOf(t[i])&&e.push(t[i]);return e}}class yn extends gn{constructor(t,e={}){const i="object"==typeof t?t:e;(!i.transports||i.transports&&"string"==typeof i.transports[0])&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(t=>cn[t]).filter(t=>!!t)),super(t,i)}}const bn="function"==typeof ArrayBuffer,mn=Object.prototype.toString,wn="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===mn.call(Blob),vn="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===mn.call(File);function In(t){return bn&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||wn&&t instanceof Blob||vn&&t instanceof File}function kn(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,i=t.length;e<i;e++)if(kn(t[e]))return!0;return!1}if(In(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return kn(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&kn(t[e]))return!0;return!1}function Sn(t){const e=[],i=t.data,r=t;return r.data=En(i,e),r.attachments=e.length,{packet:r,buffers:e}}function En(t,e){if(!t)return t;if(In(t)){const i={_placeholder:!0,num:e.length};return e.push(t),i}if(Array.isArray(t)){const i=new Array(t.length);for(let r=0;r<t.length;r++)i[r]=En(t[r],e);return i}if("object"==typeof t&&!(t instanceof Date)){const i={};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(i[r]=En(t[r],e));return i}return t}function xn(t,e){return t.data=Pn(t.data,e),delete t.attachments,t}function Pn(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let i=0;i<t.length;i++)t[i]=Pn(t[i],e);else if("object"==typeof t)for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=Pn(t[i],e));return t}const _n=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],An=5;var Nn;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(Nn||(Nn={}));class On{constructor(t){this.replacer=t}encode(t){return t.type!==Nn.EVENT&&t.type!==Nn.ACK||!kn(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===Nn.EVENT?Nn.BINARY_EVENT:Nn.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==Nn.BINARY_EVENT&&t.type!==Nn.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=Sn(t),i=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(i),r}}function Tn(t){return"[object Object]"===Object.prototype.toString.call(t)}class Cn extends Us{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const i=e.type===Nn.BINARY_EVENT;i||e.type===Nn.BINARY_ACK?(e.type=i?Nn.EVENT:Nn.ACK,this.reconstructor=new Rn(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!In(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const i={type:Number(t.charAt(0))};if(void 0===Nn[i.type])throw new Error("unknown packet type "+i.type);if(i.type===Nn.BINARY_EVENT||i.type===Nn.BINARY_ACK){const r=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const s=t.substring(r,e);if(s!=Number(s)||"-"!==t.charAt(e))throw new Error("Illegal attachments");i.attachments=Number(s)}if("/"===t.charAt(e+1)){const r=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);i.nsp=t.substring(r,e)}else i.nsp="/";const r=t.charAt(e+1);if(""!==r&&Number(r)==r){const r=e+1;for(;++e;){const i=t.charAt(e);if(null==i||Number(i)!=i){--e;break}if(e===t.length)break}i.id=Number(t.substring(r,e+1))}if(t.charAt(++e)){const r=this.tryParse(t.substr(e));if(!Cn.isPayloadValid(i.type,r))throw new Error("invalid payload");i.data=r}return i}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case Nn.CONNECT:return Tn(e);case Nn.DISCONNECT:return void 0===e;case Nn.CONNECT_ERROR:return"string"==typeof e||Tn(e);case Nn.EVENT:case Nn.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===_n.indexOf(e[0]));case Nn.ACK:case Nn.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Rn{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=xn(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function Bn(t,e,i){return t.on(e,i),function(){t.off(e,i)}}const Ln=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Mn extends Us{constructor(t,e,i){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[Bn(t,"open",this.onopen.bind(this)),Bn(t,"packet",this.onpacket.bind(this)),Bn(t,"error",this.onerror.bind(this)),Bn(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var i,r,s;if(Ln.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const n={type:Nn.EVENT,data:e,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,i=e.pop();this._registerAckCallback(t,i),n.id=t}const a=null===(r=null===(i=this.io.engine)||void 0===i?void 0:i.transport)||void 0===r?void 0:r.writable,o=this.connected&&!(null===(s=this.io.engine)||void 0===s?void 0:s._hasPingExpired());return this.flags.volatile&&!a||(o?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(t,e){var i;const r=null!==(i=this.flags.timeout)&&void 0!==i?i:this._opts.ackTimeout;if(void 0===r)return void(this.acks[t]=e);const s=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},r),n=(...t)=>{this.io.clearTimeoutFn(s),e.apply(this,t)};n.withError=!0,this.acks[t]=n}emitWithAck(t,...e){return new Promise((i,r)=>{const s=(t,e)=>t?r(t):i(e);s.withError=!0,e.push(s),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const i={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...r)=>{if(i===this._queue[0])return null!==t?i.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...r)),i.pending=!1,this._drainQueue()}),this._queue.push(i),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:Nn.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case Nn.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Nn.EVENT:case Nn.BINARY_EVENT:this.onevent(t);break;case Nn.ACK:case Nn.BINARY_ACK:this.onack(t);break;case Nn.DISCONNECT:this.ondisconnect();break;case Nn.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const i of e)i.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let i=!1;return function(...r){i||(i=!0,e.packet({type:Nn.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Nn.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let i=0;i<e.length;i++)if(t===e[i])return e.splice(i,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let i=0;i<e.length;i++)if(t===e[i])return e.splice(i,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const i of e)i.apply(this,t.data)}}}function Fn(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}Fn.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),i=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+i:t-i}return 0|Math.min(t,this.max)},Fn.prototype.reset=function(){this.attempts=0},Fn.prototype.setMin=function(t){this.ms=t},Fn.prototype.setMax=function(t){this.max=t},Fn.prototype.setJitter=function(t){this.jitter=t};class Un extends Us{constructor(t,e){var r;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,$s(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=e.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new Fn({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const s=e.parser||i;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new yn(this.uri,this.opts);const e=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const r=Bn(e,"open",function(){i.onopen(),t&&t()}),s=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},n=Bn(e,"error",s);if(!1!==this._timeout){const t=this._timeout,i=this.setTimeoutFn(()=>{r(),s(new Error("timeout")),e.close()},t);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}return this.subs.push(r),this.subs.push(n),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Bn(t,"ping",this.onping.bind(this)),Bn(t,"data",this.ondata.bind(this)),Bn(t,"error",this.onerror.bind(this)),Bn(t,"close",this.onclose.bind(this)),Bn(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){Ds(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let i=this.nsps[t];return i?this._autoConnect&&!i.active&&i.connect():(i=new Mn(this,t,e),this.nsps[t]=i),i}_destroy(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let i=0;i<e.length;i++)this.engine.write(e[i],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var i;this.cleanup(),null===(i=this.engine)||void 0===i||i.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const i=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Dn={};function Hn(t,e){"object"==typeof t&&(e=t,t=void 0);const i=function(t,e="",i){let r=t;i=i||"undefined"!=typeof location&&location,null==t&&(t=i.protocol+"//"+i.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?i.protocol+t:i.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==i?i.protocol+"//"+t:"https://"+t),r=dn(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const s=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+s+":"+r.port+e,r.href=r.protocol+"://"+s+(i&&i.port===r.port?"":":"+r.port),r}(t,(e=e||{}).path||"/socket.io"),r=i.source,s=i.id,n=i.path,a=Dn[s]&&n in Dn[s].nsps;let o;return e.forceNew||e["force new connection"]||!1===e.multiplex||a?o=new Un(r,e):(Dn[s]||(Dn[s]=new Un(r,e)),o=Dn[s]),i.query&&!e.query&&(e.query=i.queryKey),o.socket(i.path,e)}Object.assign(Hn,{Manager:Un,Socket:Mn,io:Hn,connect:Hn});class qn{socket;onDataCallback;constructor(t){this.socket=t,this.socket.on("authMessage",async t=>{void 0!==this.onDataCallback&&await this.onDataCallback(t)})}async send(t){this.socket.emit("authMessage",t)}async onData(t){this.onDataCallback=t}}class Vn{ioSocket;peer;connected=!1;id="";serverIdentityKey;eventCallbacks=new Map;constructor(t,e){this.ioSocket=t,this.peer=e,this.ioSocket.on("connect",()=>{this.connected=!0,this.id=this.ioSocket.id??"",this.fireEventCallbacks("connect")}),this.ioSocket.on("disconnect",t=>{this.connected=!1,this.fireEventCallbacks("disconnect",t)}),this.peer.listenForGeneralMessages((t,e)=>{this.serverIdentityKey=t;const{eventName:i,data:r}=this.decodeEventPayload(e);this.fireEventCallbacks(i,r)})}on(t,e){let i=this.eventCallbacks.get(t);return void 0===i&&(i=[],this.eventCallbacks.set(t,i)),i.push(e),this}emit(t,e){const i=this.encodeEventPayload(t,e);return this.peer.toPeer(i,this.serverIdentityKey).catch(e=>{console.error(`BRC103IoClientSocket emit error for event "${t}":`,e)}),this}disconnect(){this.serverIdentityKey=void 0,this.ioSocket.disconnect()}fireEventCallbacks(t,e){const i=this.eventCallbacks.get(t);if(void 0!==i)for(const t of i)t(e)}encodeEventPayload(t,e){const i={eventName:t,data:e};return Wt(JSON.stringify(i),"utf8")}decodeEventPayload(t){try{const e=Yt(t);return JSON.parse(e)}catch{return{eventName:"_unknown",data:void 0}}}}let Kn=!1;function $n(...t){Kn&&console.log(...t)}function jn(...t){Kn&&console.warn(...t)}function zn(...t){console.error(...t)}class Wn{host;authFetch;walletClient;socket;myIdentityKey;joinedRooms=new Set;lookupResolver;networkPreset;initialized=!1;socketAuthenticated=!1;connectionInitPromise;originator;constructor(t={}){const{host:e,walletClient:i,enableLogging:r=!1,networkPreset:s="mainnet",originator:n}=t,a="testnet"===s?"https://staging-messagebox.babbage.systems":"https://messagebox.babbage.systems";this.host=e?.trim()??a,this.originator=n,this.walletClient=i??new Xr("auto",n),this.authFetch=new os(this.walletClient,void 0,void 0,n),this.networkPreset=s,this.lookupResolver=new ys({networkPreset:s}),r&&(Kn=!0)}async init(t=this.host){const e=t?.trim();if(""===e)throw new Error("Cannot anoint host: No valid host provided");if(e!==this.host&&(this.initialized=!1,this.host=e),this.initialized)return;const i=await this.getIdentityKey(),[r]=await this.queryAdvertisements(i,e);if(null==r||""===r?.host?.trim()||r?.host!==e){$n("[MB CLIENT] Anointing host:",e);try{const{txid:t}=await this.anointHost(e);if(null==t||""===t.trim())throw new Error("Failed to anoint host: No transaction ID returned")}catch(t){$n("[MB CLIENT] Failed to anoint host, continuing with default functionality:",t)}}this.initialized=!0}async assertInitialized(){this.initialized&&null!=this.host&&""!==this.host.trim()||await this.init()}getJoinedRooms(){return this.joinedRooms}async getIdentityKey(){if(null!=this.myIdentityKey&&""!==this.myIdentityKey.trim())return this.myIdentityKey;$n("[MB CLIENT] Fetching identity key...");try{const t=await this.walletClient.getPublicKey({identityKey:!0},this.originator);return this.myIdentityKey=t.publicKey,$n(`[MB CLIENT] Identity key fetched: ${this.myIdentityKey}`),this.myIdentityKey}catch(t){throw zn("[MB CLIENT ERROR] Failed to fetch identity key:",t),new Error("Identity key retrieval failed")}}get testSocket(){return this.socket}async initializeConnection(t){if($n("[MB CLIENT] initializeConnection() STARTED"),null!=this.myIdentityKey&&""!==this.myIdentityKey.trim()||await this.getIdentityKey(),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw zn("[MB CLIENT ERROR] Identity key is still missing after retrieval!"),new Error("Identity key is missing");if($n("[MB CLIENT] Setting up WebSocket connection..."),!this.socketAuthenticated||null==this.socket)if(null==this.connectionInitPromise){if(null==this.socket){const e=t??this.host;if("string"!=typeof e||""===e.trim())throw new Error("Cannot initialize WebSocket: No valid host provided");this.socket=function(t,e){const i=Hn(t,e.managerOptions),r=new qn(i),s=new ss(e.wallet,r,e.requestedCertificates,e.sessionManager,void 0,e.originator);return new Vn(i,s)}(e,{wallet:this.walletClient,originator:this.originator}),this.socket.on("connect",()=>{$n("[MB CLIENT] Connected to WebSocket."),$n("[MB CLIENT] Sending authentication data:",this.myIdentityKey),null==this.myIdentityKey||""===this.myIdentityKey.trim()?zn("[MB CLIENT ERROR] Cannot send authentication: Identity key is missing!"):this.socket?.emit("authenticated",{identityKey:this.myIdentityKey})}),this.socket.on("authenticationSuccess",t=>{$n(`[MB CLIENT] WebSocket authentication successful: ${JSON.stringify(t)}`),this.socketAuthenticated=!0}),this.socket.on("authenticationFailed",t=>{zn(`[MB CLIENT ERROR] WebSocket authentication failed: ${JSON.stringify(t)}`),this.socketAuthenticated=!1}),this.socket.on("disconnect",()=>{$n("[MB CLIENT] Disconnected from MessageBox server"),this.socket=void 0,this.socketAuthenticated=!1}),this.socket.on("error",t=>{zn("[MB CLIENT ERROR] WebSocket error:",t)})}this.socket?.connected&&!this.socketAuthenticated&&this.socket.emit("authenticated",{identityKey:this.myIdentityKey}),this.connectionInitPromise=new Promise((t,e)=>{const i=this.socket;let r,s=!1;const n=()=>{s||(s=!0,null!=r&&(clearTimeout(r),r=void 0),"function"==typeof i?.off&&(i.off("authenticationSuccess",o),i.off("authenticationFailed",c),i.off("disconnect",h)),this.connectionInitPromise=void 0,$n("[MB CLIENT] WebSocket fully authenticated and ready!"),t())},a=t=>{s||(s=!0,null!=r&&(clearTimeout(r),r=void 0),"function"==typeof i?.off&&(i.off("authenticationSuccess",o),i.off("authenticationFailed",c),i.off("disconnect",h)),this.connectionInitPromise=void 0,e(t))},o=()=>{this.socketAuthenticated=!0,n()},c=()=>{this.socketAuthenticated=!1,a(new Error("[MB CLIENT ERROR] WebSocket authentication failed!"))},h=()=>{this.socketAuthenticated=!1};this.socketAuthenticated?n():(i?.on("authenticationSuccess",o),i?.on("authenticationFailed",c),i?.on("disconnect",h),r=setTimeout(()=>{this.socketAuthenticated?n():a(new Error("[MB CLIENT ERROR] WebSocket authentication timed out!"))},5e3))}),await this.connectionInitPromise}else await this.connectionInitPromise}async resolveHostForRecipient(t){const e=await this.queryAdvertisements(t,void 0);return 0===e.length?(jn(`[MB CLIENT] No advertisements for ${t}, using default host ${this.host}`),this.host):e[0].host}async queryAdvertisements(t,e){const i=[];try{const r={identityKey:t??await this.getIdentityKey()};null!=e&&""!==e.trim()&&(r.host=e);const s=await this.lookupResolver.query({service:"ls_messagebox",query:r});if("output-list"!==s.type)throw new Error(`Unexpected result type: ${String(s.type)}`);for(const t of s.outputs)try{const e=ir.fromBEEF(t.beef),r=e.outputs[t.outputIndex].lockingScript,s=Di.decode(r),[,n]=s.fields;if(null==n||0===n.length)throw new Error("Empty host field");i.push({host:Yt(n),txid:e.id("hex"),outputIndex:t.outputIndex,lockingScript:r,beef:t.beef})}catch{}}catch(t){zn("[MB CLIENT ERROR] _queryAdvertisements failed:",t)}return i}async joinRoom(t,e){if($n(`[MB CLIENT] Attempting to join WebSocket room: ${t}`),null==this.socket&&($n("[MB CLIENT] No WebSocket connection. Initializing..."),await this.initializeConnection(e)),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw new Error("[MB CLIENT ERROR] Identity key is not defined");const i=`${this.myIdentityKey??""}-${t}`;if(this.joinedRooms.has(i))$n(`[MB CLIENT] Already joined WebSocket room: ${i}`);else try{$n(`[MB CLIENT] Joining WebSocket room: ${i}`),await(this.socket?.emit("joinRoom",i)),this.joinedRooms.add(i),$n(`[MB CLIENT] Successfully joined room: ${i}`)}catch(t){zn(`[MB CLIENT ERROR] Failed to join WebSocket room: ${i}`,t)}}async listenForLiveMessages({onMessage:t,messageBox:e,overrideHost:i}){if($n(`[MB CLIENT] Setting up listener for WebSocket room: ${e}`),null==this.socket&&($n("[MB CLIENT] No WebSocket connection. Initializing..."),await this.initializeConnection(i)),await this.joinRoom(e,this.originator),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw new Error("[MB CLIENT ERROR] Identity key is missing. Cannot construct room ID.");const r=`${this.myIdentityKey}-${e}`;$n(`[MB CLIENT] Listening for messages in room: ${r}`),this.socket?.on(`sendMessage-${r}`,e=>{(async()=>{$n(`[MB CLIENT] Received message in room ${r}:`,e);try{let t=e.body;if("string"==typeof t)try{t=JSON.parse(t)}catch{}if(null!=t&&"object"==typeof t&&"string"==typeof t.encryptedMessage){$n(`[MB CLIENT] Decrypting message from ${String(e.sender)}...`);const i=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:e.sender,ciphertext:Wt(t.encryptedMessage,"base64")},this.originator);e.body=Yt(i.plaintext)}else $n("[MB CLIENT] Message is not encrypted."),e.body="string"==typeof t?t:(()=>{try{return JSON.stringify(t)}catch{return"[Error: Unstringifiable message]"}})()}catch(t){zn("[MB CLIENT ERROR] Failed to parse or decrypt live message:",t),e.body="[Error: Failed to decrypt or parse message]"}t(e)})()})}async sendLiveMessage({recipient:t,messageBox:e,body:i,messageId:r,skipEncryption:s,checkPermissions:n},a){if(null==t||""===t.trim())throw new Error("[MB CLIENT ERROR] Recipient identity key is required");if(null==e||""===e.trim())throw new Error("[MB CLIENT ERROR] MessageBox is required");if(null==i||"string"==typeof i&&""===i.trim())throw new Error("[MB CLIENT ERROR] Message body cannot be empty");if(await this.joinRoom(e,this.originator),null==this.socket||!this.socket.connected){jn("[MB CLIENT WARNING] WebSocket not connected, falling back to HTTP");const r=a??await this.resolveHostForRecipient(t);return await this.sendMessage({recipient:t,messageBox:e,body:i},r)}let o;try{const e=await this.walletClient.createHmac({data:Array.from((new TextEncoder).encode(JSON.stringify(i))),protocolID:[1,"messagebox"],keyID:"1",counterparty:t},this.originator);o=r??Array.from(e.hmac).map(t=>t.toString(16).padStart(2,"0")).join("")}catch(t){throw zn("[MB CLIENT ERROR] Failed to generate HMAC:",t),new Error("Failed to generate message identifier.")}const c=`${t}-${e}`;let h;if($n(`[MB CLIENT] Sending WebSocket message to room: ${c}`),!0===s)h="string"==typeof i?i:JSON.stringify(i);else{const e=await this.walletClient.encrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t,plaintext:Wt("string"==typeof i?i:JSON.stringify(i),"utf8")},this.originator);h=JSON.stringify({encryptedMessage:Zt(e.ciphertext)})}return await new Promise((r,a)=>{const u=`sendMessageAck-${c}`;let d,l=!1;const f=c=>{if(l)return;l=!0,null!=d&&(clearTimeout(d),d=void 0);const h=this.socket;if("function"==typeof h?.off&&h.off(u,f),$n("[MB CLIENT] Received WebSocket acknowledgment:",c),null==c||"success"!==c.status){jn("[MB CLIENT] WebSocket message failed or returned unexpected response. Falling back to HTTP.");const c={recipient:t,messageBox:e,body:i,messageId:o,skipEncryption:s,checkPermissions:n};this.resolveHostForRecipient(t).then(async t=>await this.sendMessage(c,t)).then(r).catch(a)}else $n("[MB CLIENT] Message sent successfully via WebSocket:",c),r(c)};this.socket?.on(u,f),this.socket?.emit("sendMessage",{roomId:c,message:{messageId:o,recipient:t,body:h}}),d=setTimeout(()=>{if(!l){l=!0,d=void 0;const c=this.socket;"function"==typeof c?.off&&c.off(u,f),jn("[CLIENT] WebSocket acknowledgment timed out, falling back to HTTP");const h={recipient:t,messageBox:e,body:i,messageId:o,skipEncryption:s,checkPermissions:n};this.resolveHostForRecipient(t).then(async t=>await this.sendMessage(h,t)).then(r).catch(a)}},1e4)})}async leaveRoom(t){if(await this.assertInitialized(),null==this.socket)return void jn("[MB CLIENT] Attempted to leave a room but WebSocket is not connected.");if(null==this.myIdentityKey||""===this.myIdentityKey.trim())throw new Error("[MB CLIENT ERROR] Identity key is not defined");const e=`${this.myIdentityKey}-${t}`;$n(`[MB CLIENT] Leaving WebSocket room: ${e}`),this.socket.emit("leaveRoom",e),this.joinedRooms.delete(e)}async disconnectWebSocket(){await this.assertInitialized(),null!=this.socket?($n("[MB CLIENT] Closing WebSocket connection..."),this.socket.disconnect(),this.socket=void 0):$n("[MB CLIENT] No active WebSocket connection to close.")}async sendMessage(t,e){if(await this.assertInitialized(),null==t.recipient||""===t.recipient.trim())throw new Error("You must provide a message recipient!");if(null==t.messageBox||""===t.messageBox.trim())throw new Error("You must provide a messageBox to send this message into!");if(null==t.body||"string"==typeof t.body&&0===t.body.trim().length)throw new Error("Every message must have a body!");let i,r,s;if(!0===t.checkPermissions)try{$n("[MB CLIENT] Checking permissions and fees for message...");const r=await this.getMessageBoxQuote({recipient:t.recipient,messageBox:t.messageBox},e);if(-1===r.recipientFee)throw new Error("You have been blocked from sending messages to this recipient.");if(r.recipientFee>0||r.deliveryFee>0){const s=r.recipientFee+r.deliveryFee;s>0&&($n(`[MB CLIENT] Creating payment of ${s} sats for message...`),i=await this.createMessagePayment(t.recipient,r,e),$n("[MB CLIENT] Payment data prepared:",i))}}catch(t){throw new Error(`Permission check failed: ${t instanceof Error?t.message:"Unknown error"}`)}try{const e=await this.walletClient.createHmac({data:Array.from((new TextEncoder).encode(JSON.stringify(t.body))),protocolID:[1,"messagebox"],keyID:"1",counterparty:t.recipient},this.originator);r=t.messageId??Array.from(e.hmac).map(t=>t.toString(16).padStart(2,"0")).join("")}catch(t){throw zn("[MB CLIENT ERROR] Failed to generate HMAC:",t),new Error("Failed to generate message identifier.")}if(!0===t.skipEncryption)s="string"==typeof t.body?t.body:JSON.stringify(t.body);else{const e=await this.walletClient.encrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t.recipient,plaintext:Wt("string"==typeof t.body?t.body:JSON.stringify(t.body),"utf8")},this.originator);s=JSON.stringify({encryptedMessage:Zt(e.ciphertext)})}const n={message:{...t,messageId:r,body:s},...null!=i&&{payment:i}};try{const i=e??await this.resolveHostForRecipient(t.recipient);if($n("[MB CLIENT] Sending HTTP request to:",`${i}/sendMessage`),$n("[MB CLIENT] Request Body:",JSON.stringify(n,null,2)),null==this.myIdentityKey||""===this.myIdentityKey)try{const t=await this.walletClient.getPublicKey({identityKey:!0},this.originator);this.myIdentityKey=t.publicKey,$n(`[MB CLIENT] Fetched identity key before sending request: ${this.myIdentityKey}`)}catch(t){throw zn("[MB CLIENT ERROR] Failed to fetch identity key:",t),new Error("Identity key retrieval failed")}const s=await this.authFetch.fetch(`${i}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(s.bodyUsed)throw new Error("[MB CLIENT ERROR] Response body has already been used!");const a=await s.json();if($n("[MB CLIENT] Raw Response Body:",a),!s.ok)throw zn(`[MB CLIENT ERROR] Failed to send message. HTTP ${s.status}: ${s.statusText}`),new Error(`Message sending failed: HTTP ${s.status} - ${s.statusText}`);if("success"!==a.status)throw zn(`[MB CLIENT ERROR] Server returned an error: ${String(a.description)}`),new Error(a.description??"Unknown error from server.");return $n("[MB CLIENT] Message successfully sent."),{...a,messageId:r}}catch(t){zn("[MB CLIENT ERROR] Network or timeout error:",t);const e=t instanceof Error?t.message:"Unknown error";throw new Error(`Failed to send message: ${e}`)}}async sendMesagetoRecepients(t,e){await this.assertInitialized();const{recipients:i,messageBox:r,body:s,skipEncryption:n}=t;if(!Array.isArray(i)||0===i.length)throw new Error("You must provide at least one recipient!");if(!r||""===r.trim())throw new Error("You must provide a messageBox to send this message into!");if(null==s||"string"==typeof s&&0===s.trim().length)throw new Error("Every message must have a body!");const a=await this.getMessageBoxQuote({recipient:i,messageBox:r},e),o=Array.isArray(a?.quotesByRecipient)?a.quotesByRecipient:[],c=a?.blockedRecipients??[],h=a?.totals,u=i.filter(t=>!c.includes(t));if(0===u.length)return{status:"error",description:`All ${i.length} recipients are blocked.`,sent:[],blocked:c,failed:i.map(t=>({recipient:t,error:"blocked"})),totals:h};const d=new Map;for(const t of o)d.set(t.recipient,{recipientFee:t.recipientFee,deliveryFee:t.deliveryFee});const{deliveryAgentIdentityKeyByHost:l}=a;if(!l||0===Object.keys(l).length)throw new Error("Missing delivery agent identity keys in quote response.");if(Object.keys(l).length>1&&!e)throw new Error("Recipients resolve to multiple hosts. Use overrideHost to force a single server or split by host.");const f=(e??await this.resolveHostForRecipient(u[0])).replace(/\/+$/,""),p=l[f]??Object.values(l)[0];if(!p)throw new Error("Could not determine server delivery agent identity key.");if(!this.myIdentityKey){const t=await this.walletClient.getPublicKey({identityKey:!0},this.originator);this.myIdentityKey=t.publicKey}const g=Array.from((new TextEncoder).encode(JSON.stringify(s))),y=await this.mapWithConcurrency(u,8,async t=>{const e=await this.walletClient.createHmac({data:g,protocolID:[1,"messagebox"],keyID:"1",counterparty:t},this.originator);return Array.from(e.hmac).map(t=>t.toString(16).padStart(2,"0")).join("")});let b;b="string"==typeof s?s:JSON.stringify(s);const m=await this.createMessagePaymentBatch(u,d,p),w={message:{recipients:u,messageBox:r,messageId:y,body:b},payment:m};$n("[MB CLIENT] Sending HTTP request to:",`${f}/sendMessage`),$n("[MB CLIENT] Request Body (batch):",JSON.stringify({...w,payment:{...m,tx:"<omitted>"}},null,2));try{const t=await this.authFetch.fetch(`${f}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)}),e=await t.json().catch(()=>({}));if(!t.ok||"success"!==e.status){const i=t.ok?e.description??"Unknown server error":`HTTP ${t.status} - ${t.statusText}`;throw new Error(i)}const i=Array.isArray(e.results)?e.results:[],r=[],s=i.length===u.length?"success":i.length>0?"partial":"error";return{status:s,description:"success"===s?`Sent to ${i.length} recipients.`:"partial"===s?`Sent to ${i.length} recipients; ${u.length-i.length} failed; ${c.length} blocked.`:`Failed to send to ${u.length} allowed recipients. ${c.length} blocked.`,sent:i,blocked:c,failed:r,totals:h}}catch(t){const e=t instanceof Error?t.message:"Unknown error";return{status:"error",description:`Batch send failed: ${e}`,sent:[],blocked:c,failed:u.map(t=>({recipient:t,error:e})),totals:h}}}async anointHost(t){$n("[MB CLIENT] Starting anointHost...");try{if(!t.startsWith("http"))throw new Error("Invalid host URL");const e=await this.getIdentityKey();$n("[MB CLIENT] Fields - Identity:",e,"Host:",t);const i=[Wt(e,"hex"),Wt(t,"utf8")],r=new Di(this.walletClient,this.originator);$n("Fields:",i.map(t=>jt(t))),$n("ProtocolID:",[1,"messagebox advertisement"]),$n("KeyID:","1"),$n("SignAs:","self"),$n("anyoneCanSpend:",!1),$n("forSelf:",!0);const s=await r.lock(i,[1,"messagebox advertisement"],"1","anyone",!0);$n("[MB CLIENT] PushDrop script:",s.toASM());const{tx:n,txid:a}=await this.walletClient.createAction({description:"Anoint host for overlay routing",outputs:[{basket:"overlay advertisements",lockingScript:s.toHex(),satoshis:1,outputDescription:"Overlay advertisement output"}],options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1}},this.originator);if($n("[MB CLIENT] Transaction created:",a),void 0!==n){const t=new ms(["tm_messagebox"],{networkPreset:this.networkPreset}),e=await t.broadcast(ir.fromAtomicBEEF(n));if($n("[MB CLIENT] Advertisement broadcast succeeded. TXID:",e.txid),"string"!=typeof e.txid)throw new Error("Anoint failed: broadcast did not return a txid");return{txid:e.txid}}throw new Error("Anoint failed: failed to create action!")}catch(t){throw zn("[MB CLIENT ERROR] anointHost threw:",t),t}}async revokeHostAdvertisement(t){$n("[MB CLIENT] Starting revokeHost...");const e=`${t.txid}.${t.outputIndex}`;try{const{signableTransaction:i}=await this.walletClient.createAction({description:"Revoke MessageBox host advertisement",inputBEEF:t.beef,inputs:[{outpoint:e,unlockingScriptLength:73,inputDescription:"Revoking host advertisement token"}]},this.originator);if(void 0===i)throw new Error("Failed to create signable transaction.");const r=ir.fromBEEF(i.tx),s=new Di(this.walletClient,this.originator),n=await s.unlock([1,"messagebox advertisement"],"1","anyone","all",!1,t.outputIndex,t.lockingScript),a=await n.sign(r,t.outputIndex),{tx:o}=await this.walletClient.signAction({reference:i.reference,spends:{[t.outputIndex]:{unlockingScript:a.toHex()}},options:{acceptDelayedBroadcast:!1}},this.originator);if(void 0===o)throw new Error("Failed to finalize the transaction signature.");const c=new ms(["tm_messagebox"],{networkPreset:this.networkPreset}),h=await c.broadcast(ir.fromAtomicBEEF(o));if($n("[MB CLIENT] Revocation broadcast succeeded. TXID:",h.txid),"string"!=typeof h.txid)throw new Error("Revoke failed: broadcast did not return a txid");return{txid:h.txid}}catch(t){throw zn("[MB CLIENT ERROR] revokeHost threw:",t),t}}async listMessages({messageBox:t,host:e,acceptPayments:i}){if("boolean"!=typeof i&&(i=!0),""===t.trim())throw new Error("MessageBox cannot be empty");let r=null!=e?[e]:[];if(0===r.length){const t=await this.queryAdvertisements(await this.getIdentityKey(),void 0);r=Array.from(new Set([this.host,...t.map(t=>t.host)]))}const s=await Promise.allSettled(r.map(async e=>{try{$n(`[MB CLIENT] Listing messages from ${e}…`);const i=await this.authFetch.fetch(`${e}/listMessages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageBox:t})});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);const r=await i.json();if("error"===r.status)throw new Error(r.description??"Unknown server error");return r.messages}catch(t){throw $n(`[MB CLIENT DEBUG] listMessages failed for ${e}:`,t),t}})),n=[],a=[];for(const t of s)"fulfilled"===t.status?n.push(t.value):a.push(t.reason);if(0===n.length)throw new Error("Failed to retrieve messages from any host");const o=new Map;for(const t of n)for(const e of t)o.has(e.messageId)||o.set(e.messageId,e);if(0===o.size)return[];const c=Array.from(o.values()),h=c.map(t=>{const e="string"==typeof t.body?this.tryParse(t.body):t.body;let i,r=e;if(null!=e&&"object"==typeof e&&"message"in e){const t=e.message;r="string"==typeof t?this.tryParse(t):t,i=e.payment}return{message:t,parsedBody:e,messageContent:r,paymentData:i}});if(i){const t=h.filter(t=>null!=t.paymentData?.tx&&null!=t.paymentData.outputs);await this.mapWithConcurrency(t,2,async t=>{try{$n(`[MB CLIENT] Processing recipient payment in message from ${String(t.message.sender)}…`);const e=t.paymentData.outputs.filter(t=>"wallet payment"===t.protocol);e.length>0?($n(`[MB CLIENT] Internalizing ${e.length} recipient payment output(s)…`),(await this.walletClient.internalizeAction({tx:t.paymentData.tx,outputs:e,description:t.paymentData.description??"MessageBox recipient payment"},this.originator)).accepted?$n("[MB CLIENT] Successfully internalized recipient payment"):jn("[MB CLIENT] Recipient payment internalization was not accepted")):$n("[MB CLIENT] No wallet payment outputs found in payment data")}catch(t){zn("[MB CLIENT ERROR] Failed to internalize recipient payment:",t)}return null})}return await this.mapWithConcurrency(h,4,async t=>{try{if(null!=t.messageContent&&"object"==typeof t.messageContent&&"string"==typeof t.messageContent.encryptedMessage){$n(`[MB CLIENT] Decrypting message from ${String(t.message.sender)}…`);const e=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t.message.sender,ciphertext:Wt(t.messageContent.encryptedMessage,"base64")},this.originator),i=Yt(e.plaintext);t.message.body=this.tryParse(i)}else t.message.body=t.messageContent??t.parsedBody}catch(e){zn("[MB CLIENT ERROR] Failed to parse or decrypt message in list:",e),t.message.body="[Error: Failed to decrypt or parse message]"}return null}),c.sort((t,e)=>Number(e.timestamp??0)-Number(t.timestamp??0)),c}async listMessagesLite({messageBox:t,host:e}){const i=await this.authFetch.fetch(`${e}/listMessages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageBox:t})}),r=await i.json();if("error"===r.status)throw new Error(r.description??"Unknown server error");const s=r.messages,n=t=>{try{return JSON.parse(t)}catch{return t}};return await this.mapWithConcurrency(s,4,async t=>{try{const e="string"==typeof t.body?n(t.body):t.body;let i=e;if(null!=e&&"object"==typeof e&&"message"in e){const t=e.message;i="string"==typeof t?n(t):t}if(null!=i&&"object"==typeof i&&"string"==typeof i.encryptedMessage){const e=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t.sender,ciphertext:Wt(i.encryptedMessage,"base64")}),r=Yt(e.plaintext);t.body=n(r)}else t.body=i??e}catch(e){zn("[MB CLIENT ERROR] Failed to parse or decrypt message in list:",e),t.body="[Error: Failed to decrypt or parse message]"}return null}),s}tryParse(t){try{return JSON.parse(t)}catch{return t}}async mapWithConcurrency(t,e,i){if(0===t.length)return[];if(!Number.isFinite(e)||e>=t.length)return await Promise.all(t.map(i));const r=Math.max(1,Math.min(e,t.length)),s=new Array(t.length);let n=0;const a=Array.from({length:r},async()=>{for(;;){const e=n;if(n++,e>=t.length)return;s[e]=await i(t[e],e)}});return await Promise.all(a),s}async acknowledgeNotification(t){await this.acknowledgeMessage({messageIds:[t.messageId]});const e="string"==typeof t.body?this.tryParse(t.body):t.body;let i;if(null!=e&&"object"==typeof e&&"message"in e&&(i=e.payment),null!=i?.tx&&null!=i.outputs)try{$n(`[MB CLIENT] Processing recipient payment in message from ${String(t.sender)}…`);const e=i.outputs.filter(t=>"wallet payment"===t.protocol);return e.length<1?($n("[MB CLIENT] No wallet payment outputs found in payment data"),!1):($n(`[MB CLIENT] Internalizing ${e.length} recipient payment output(s)…`),(await this.walletClient.internalizeAction({tx:i.tx,outputs:e,description:i.description??"MessageBox recipient payment"})).accepted?($n("[MB CLIENT] Successfully internalized recipient payment"),!0):(jn("[MB CLIENT] Recipient payment internalization was not accepted"),!1))}catch(t){return zn("[MB CLIENT ERROR] Failed to internalize recipient payment:",t),!1}return!1}async acknowledgeMessage({messageIds:t,host:e}){if(!Array.isArray(t)||0===t.length)throw new Error("Message IDs array cannot be empty");$n(`[MB CLIENT] Acknowledging messages ${JSON.stringify(t)}…`);let i=null!=e?[e]:[];if(0===i.length){const t=await this.getIdentityKey(),e=await this.queryAdvertisements(t,void 0);i=Array.from(new Set([this.host,...e.map(t=>t.host)]))}const r=await Promise.allSettled(i.map(async e=>{try{const i=await this.authFetch.fetch(`${e}/acknowledgeMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageIds:t})});if(!i.ok)throw new Error(`HTTP ${i.status}`);const r=await i.json();if("error"===r.status)throw new Error(r.description);return $n(`[MB CLIENT] Acknowledged on ${e}`),r.status}catch(t){return jn(`[MB CLIENT WARN] acknowledgeMessage failed for ${e}:`,t),null}})),s=r.filter(t=>"fulfilled"===t.status),n=s.find(t=>null!=t.value)?.value;if(null!=n)return n;const a=[];for(const t of r)"rejected"===t.status&&a.push(t.reason);throw new Error(`Failed to acknowledge messages on all hosts: ${a.map(t=>String(t)).join("; ")}`)}async setMessageBoxPermission(t,e){const i=e??this.host;$n("[MB CLIENT] Setting messageBox permission...");const r=await this.authFetch.fetch(`${i}/permissions/set`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageBox:t.messageBox,recipientFee:t.recipientFee,...null!=t.sender&&{sender:t.sender}})});if(!r.ok){const t=await r.json().catch(()=>({}));throw new Error(`Failed to set permission: HTTP ${r.status} - ${""!==String(t.description)?String(t.description):r.statusText}`)}const{status:s,description:n}=await r.json();if("error"===s)throw new Error(n??"Failed to set permission")}async getMessageBoxPermission(t,e){const i=e??await this.resolveHostForRecipient(t.recipient),r=new URLSearchParams({recipient:t.recipient,messageBox:t.messageBox,...null!=t.sender&&{sender:t.sender}});$n("[MB CLIENT] Getting messageBox permission...");const s=await this.authFetch.fetch(`${i}/permissions/get?${r.toString()}`,{method:"GET"});if(!s.ok){const t=await s.json().catch(()=>({}));throw new Error(`Failed to get permission: HTTP ${s.status} - ${""!==String(t.description)?String(t.description):s.statusText}`)}const n=await s.json();if("error"===n.status)throw new Error(n.description??"Failed to get permission");return n.permission}async getMessageBoxQuote(t,e){if(!Array.isArray(t.recipient)){const i=e??await this.resolveHostForRecipient(t.recipient),r=new URLSearchParams({recipient:t.recipient,messageBox:t.messageBox});$n("[MB CLIENT] Getting messageBox quote (single)..."),console.log("HELP IM QUOTING",`${i}/permissions/quote?${r.toString()}`);const s=await this.authFetch.fetch(`${i}/permissions/quote?${r.toString()}`,{method:"GET"});if(console.log("server response from getquote]",s),!s.ok){const t=await s.json().catch(()=>({}));throw new Error(`Failed to get quote: HTTP ${s.status} - ${String(t.description)??s.statusText}`)}const{status:n,description:a,quote:o}=await s.json();if("error"===n)throw new Error(a??"Failed to get quote");const c=s.headers.get("x-bsv-auth-identity-key");if(console.log("deliveryAgentIdentityKey",c),null==c)throw new Error("Failed to get quote: Delivery agent did not provide their identity key");return{recipientFee:o.recipientFee,deliveryFee:o.deliveryFee,deliveryAgentIdentityKey:c}}const i=t.recipient;if(0===i.length)throw new Error("At least one recipient is required.");$n("[MB CLIENT] Getting messageBox quotes (multi)..."),console.log("[MB CLIENT] Getting messageBox quotes (multi)...");const r=new Map,s=null!=e?i.map(()=>e):await this.mapWithConcurrency(i,8,async t=>await this.resolveHostForRecipient(t));for(let t=0;t<i.length;t++){const e=i[t],n=s[t],a=r.get(n);null!=a?a.push(e):r.set(n,[e])}const n={},a=[],o=[];let c=0,h=0;const u=async(e,i)=>{const r=new URLSearchParams;for(const t of i)r.append("recipient",t);r.set("messageBox",t.messageBox);const s=`${e}/permissions/quote?${r.toString()}`;$n("[MB CLIENT] Multi-quote GET:",s);const u=await this.authFetch.fetch(s,{method:"GET"});if(!u.ok){const t=await u.json().catch(()=>({}));throw new Error(`Failed to get quote (host ${e}): HTTP ${u.status} - ${String(t.description)??u.statusText}`)}const d=u.headers.get("x-bsv-auth-identity-key");if(!d)throw new Error(`Failed to get quote (host ${e}): missing delivery agent identity key`);n[e]=d;const l=await u.json();if(Array.isArray(l?.quotesByRecipient)){for(const t of l.quotesByRecipient)a.push({recipient:t.recipient,messageBox:t.messageBox,deliveryFee:t.deliveryFee,recipientFee:t.recipientFee,status:t.status}),c+=t.deliveryFee,-1===t.recipientFee?o.includes(t.recipient)||o.push(t.recipient):h+=t.recipientFee;if(Array.isArray(l?.blockedRecipients))for(const t of l.blockedRecipients)o.includes(t)||o.push(t)}else{if(!l?.quote)throw new Error(`Unexpected quote response shape from host ${e}`);for(const e of i){const{deliveryFee:i,recipientFee:r}=l.quote,s=-1===r?"blocked":0===r?"always_allow":"payment_required";a.push({recipient:e,messageBox:t.messageBox,deliveryFee:i,recipientFee:r,status:s}),c+=i,-1===r?o.push(e):h+=r}}};return await Promise.all(Array.from(r.entries()).map(async([t,e])=>await u(t,e))),{quotesByRecipient:a,totals:{deliveryFees:c,recipientFees:h,totalForPayableRecipients:c+h},blockedRecipients:o,deliveryAgentIdentityKeyByHost:n}}async listMessageBoxPermissions(t,e){const i=e??this.host,r=new URLSearchParams;null!=t?.messageBox&&r.set("message_box",t.messageBox),void 0!==t?.limit&&r.set("limit",t.limit.toString()),void 0!==t?.offset&&r.set("offset",t.offset.toString()),$n("[MB CLIENT] Listing messageBox permissions with params:",r.toString());const s=await this.authFetch.fetch(`${i}/permissions/list?${r.toString()}`,{method:"GET"});if(!s.ok){const t=await s.json().catch(()=>({}));throw new Error(`Failed to list permissions: HTTP ${s.status} - ${""!==String(t.description)?String(t.description):s.statusText}`)}const n=await s.json();if("error"===n.status)throw new Error(n.description??"Failed to list permissions");return n.permissions.map(t=>({sender:t.sender,messageBox:t.message_box,recipientFee:t.recipient_fee,status:Wn.getStatusFromFee(t.recipient_fee),createdAt:t.created_at,updatedAt:t.updated_at}))}async allowNotificationsFromPeer(t,e=0,i){await this.setMessageBoxPermission({messageBox:"notifications",sender:t,recipientFee:e},i)}async denyNotificationsFromPeer(t,e){await this.setMessageBoxPermission({messageBox:"notifications",sender:t,recipientFee:-1},e)}async checkPeerNotificationStatus(t,e){const i=await this.getIdentityKey();return await this.getMessageBoxPermission({recipient:i,messageBox:"notifications",sender:t},e)}async listPeerNotifications(t){return await this.listMessageBoxPermissions({messageBox:"notifications"},t)}async sendNotification(t,e,i){return await this.assertInitialized(),Array.isArray(t)?await this.sendMesagetoRecepients({recipients:t,messageBox:"notifications",body:e},i):await this.sendMessage({recipient:t,messageBox:"notifications",body:e,checkPermissions:!0},i)}async registerDevice(t,e){if(null==t.fcmToken||""===t.fcmToken.trim())throw new Error("fcmToken is required and must be a non-empty string");if(null!=t.platform&&!["ios","android","web"].includes(t.platform))throw new Error("platform must be one of: ios, android, web");const i=e??this.host;$n("[MB CLIENT] Registering device for FCM notifications...");const r=await this.authFetch.fetch(`${i}/registerDevice`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fcmToken:t.fcmToken.trim(),deviceId:t.deviceId?.trim()??void 0,platform:t.platform??void 0})});if(!r.ok){const t=await r.json().catch(()=>({})),e=String(t.description)??r.statusText;throw new Error(`Failed to register device: HTTP ${r.status} - ${e}`)}const s=await r.json();if("error"===s.status)throw new Error(s.description??"Failed to register device");return $n("[MB CLIENT] Device registered successfully"),{status:s.status,message:s.message,deviceId:s.deviceId}}async listRegisteredDevices(t){const e=t??this.host;$n("[MB CLIENT] Listing registered devices...");const i=await this.authFetch.fetch(`${e}/devices`,{method:"GET"});if(!i.ok){const t=await i.json().catch(()=>({})),e=String(t.description)??i.statusText;throw new Error(`Failed to list devices: HTTP ${i.status} - ${e}`)}const r=await i.json();if("error"===r.status)throw new Error(r.description??"Failed to list devices");return $n(`[MB CLIENT] Found ${r.devices.length} registered devices`),r.devices}static getStatusFromFee(t){return-1===t?"blocked":0===t?"always_allow":"payment_required"}async createMessagePayment(t,e,i="MessageBox delivery payment"){if(e.recipientFee<=0&&e.deliveryFee<=0)throw new Error("No payment required");$n(`[MB CLIENT] Creating payment transaction for ${e.recipientFee} sats (delivery: ${e.deliveryFee}, recipient: ${e.recipientFee})`);const r=[],s=[],n=await this.getIdentityKey();let a=0;if(e.deliveryFee>0){const t=Zt(We(32)),i=Zt(We(32));console.log("delivery agent:",e.deliveryAgentIdentityKey);const{publicKey:o}=await this.walletClient.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${t} ${i}`,counterparty:e.deliveryAgentIdentityKey},this.originator),c=(new Fi).lock($e.fromString(o).toAddress()).toHex();s.push({satoshis:e.deliveryFee,lockingScript:c,outputDescription:"MessageBox server delivery fee",customInstructions:JSON.stringify({derivationPrefix:t,derivationSuffix:i,recipientIdentityKey:e.deliveryAgentIdentityKey})}),r.push({outputIndex:a++,protocol:"wallet payment",paymentRemittance:{derivationPrefix:t,derivationSuffix:i,senderIdentityKey:n}})}if(e.recipientFee>0){const i=Zt(We(32)),n=Zt(We(32)),o=new ar("anyone"),{publicKey:c}=await o.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${i} ${n}`,counterparty:t});if(null==c||""===c.trim())throw new Error("Failed to derive recipient's public key");const h=(new Fi).lock($e.fromString(c).toAddress()).toHex();s.push({satoshis:e.recipientFee,lockingScript:h,outputDescription:"Recipient message fee",customInstructions:JSON.stringify({derivationPrefix:i,derivationSuffix:n,recipientIdentityKey:t})}),r.push({outputIndex:a++,protocol:"wallet payment",paymentRemittance:{derivationPrefix:i,derivationSuffix:n,senderIdentityKey:(await o.getPublicKey({identityKey:!0})).publicKey}})}const{tx:o}=await this.walletClient.createAction({description:i,outputs:s,options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1}},this.originator);if(null==o)throw new Error("Failed to create payment transaction");return{tx:o,outputs:r,description:i}}async createMessagePaymentBatch(t,e,i,r="MessageBox delivery payment (batch)"){const s=[],n=[],a=t.reduce((t,i)=>{const r=e.get(i);return null!=r?t??r.deliveryFee:t},void 0)??0,o=await this.getIdentityKey();let c=0;if(a>0){const t=Zt(We(32)),e=Zt(We(32)),{publicKey:r}=await this.walletClient.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${t} ${e}`,counterparty:i},this.originator),h=(new Fi).lock($e.fromString(r).toAddress()).toHex();n.push({satoshis:a,lockingScript:h,outputDescription:"MessageBox server delivery fee (batch)",customInstructions:JSON.stringify({derivationPrefix:t,derivationSuffix:e,recipientIdentityKey:i})}),s.push({outputIndex:c++,protocol:"wallet payment",paymentRemittance:{derivationPrefix:t,derivationSuffix:e,senderIdentityKey:o}})}const h=new ar("anyone"),u=(await h.getPublicKey({identityKey:!0})).publicKey;for(const i of t){const t=e.get(i);if(null==t||t.recipientFee<=0)continue;const r=Zt(We(32)),a=Zt(We(32)),{publicKey:o}=await h.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${r} ${a}`,counterparty:i}),d=(new Fi).lock($e.fromString(o).toAddress()).toHex();n.push({satoshis:t.recipientFee,lockingScript:d,outputDescription:`Recipient message fee (${i.slice(0,8)}…)`,customInstructions:JSON.stringify({derivationPrefix:r,derivationSuffix:a,recipientIdentityKey:i})}),s.push({outputIndex:c++,protocol:"wallet payment",paymentRemittance:{derivationPrefix:r,derivationSuffix:a,senderIdentityKey:u}})}const{tx:d}=await this.walletClient.createAction({description:r,outputs:n,options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1}},this.originator);if(null==d)throw new Error("Failed to create payment transaction");return{tx:d,outputs:s,description:r}}}function Gn(t){try{return"string"==typeof t?JSON.parse(t):t}catch(e){return zn("[PP CLIENT] Failed to parse input in safeParse:",t),{}}}const Xn="payment_inbox";class Yn extends Wn{peerPayWalletClient;_authFetchInstance;messageBox;constructor(t){const{messageBoxHost:e="https://messagebox.babbage.systems",walletClient:i,enableLogging:r=!1,originator:s}=t;super({host:e,walletClient:i,enableLogging:r,originator:s}),this.messageBox=t.messageBox??Xn,this.peerPayWalletClient=i,this.originator=s}get authFetchInstance(){return null!==this._authFetchInstance&&void 0!==this._authFetchInstance||(this._authFetchInstance=new os(this.peerPayWalletClient,void 0,void 0,this.originator)),this._authFetchInstance}async createPaymentToken(t){if(t.amount<=0)throw new Error("Invalid payment details: recipient and valid amount are required");const e=await Qr(this.peerPayWalletClient,"self",this.originator),i=await Qr(this.peerPayWalletClient,"self",this.originator);$n(`[PP CLIENT] Derivation Prefix: ${e}`),$n(`[PP CLIENT] Derivation Suffix: ${i}`);const{publicKey:r}=await this.peerPayWalletClient.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${e} ${i}`,counterparty:t.recipient},this.originator);if($n(`[PP CLIENT] Derived Public Key: ${r}`),null==r||""===r.trim())throw new Error("Failed to derive recipient’s public key");const s=(new Fi).lock($e.fromString(r).toAddress()).toHex();$n(`[PP CLIENT] Locking Script: ${s}`);const n=await this.peerPayWalletClient.createAction({description:"PeerPay payment",labels:["peerpay"],outputs:[{satoshis:t.amount,lockingScript:s,customInstructions:JSON.stringify({derivationPrefix:e,derivationSuffix:i,payee:t.recipient}),outputDescription:"Payment for PeerPay transaction"}],options:{randomizeOutputs:!1}},this.originator);if(void 0===n.tx)throw new Error("Transaction creation failed!");return $n("[PP CLIENT] Payment Action:",n),{customInstructions:{derivationPrefix:e,derivationSuffix:i},transaction:n.tx,amount:t.amount}}async sendPayment(t,e){if(null==t.recipient||""===t.recipient.trim()||t.amount<=0)throw new Error("Invalid payment details: recipient and valid amount are required");const i=await this.createPaymentToken(t);await this.sendMessage({recipient:t.recipient,messageBox:this.messageBox,body:JSON.stringify(i)},e)}async sendLivePayment(t,e){const i=await this.createPaymentToken(t);try{await this.sendLiveMessage({recipient:t.recipient,messageBox:this.messageBox,body:JSON.stringify(i)},e)}catch(r){jn("[PP CLIENT] sendLiveMessage failed, falling back to HTTP:",r),await this.sendMessage({recipient:t.recipient,messageBox:this.messageBox,body:JSON.stringify(i)},e)}}async listenForLivePayments({onPayment:t,overrideHost:e}){await this.listenForLiveMessages({messageBox:this.messageBox,overrideHost:e,onMessage:e=>{$n("[MB CLIENT] Received Live Payment:",e);const i={messageId:e.messageId,sender:e.sender,token:Gn(e.body)};$n("[PP CLIENT] Converted PeerMessage to IncomingPayment:",i),t(i)}})}async acceptPayment(t){try{$n(`[PP CLIENT] Processing payment: ${JSON.stringify(t,null,2)}`);const e=await this.peerPayWalletClient.internalizeAction({tx:t.token.transaction,outputs:[{paymentRemittance:{derivationPrefix:t.token.customInstructions.derivationPrefix,derivationSuffix:t.token.customInstructions.derivationSuffix,senderIdentityKey:t.sender},outputIndex:t.token.outputIndex??0,protocol:"wallet payment"}],labels:["peerpay"],description:"PeerPay Payment"},this.originator);return $n(`[PP CLIENT] Payment internalized successfully: ${JSON.stringify(e,null,2)}`),$n(`[PP CLIENT] Acknowledging payment with messageId: ${t.messageId}`),await this.acknowledgeMessage({messageIds:[t.messageId]}),{payment:t,paymentResult:e}}catch(t){return zn(`[PP CLIENT] Error accepting payment: ${String(t)}`),"Unable to receive payment!"}}async rejectPayment(t){if($n(`[PP CLIENT] Rejecting payment: ${JSON.stringify(t,null,2)}`),t.token.amount-1e3<1e3){$n("[PP CLIENT] Payment amount too small after fee, just acknowledging.");try{$n(`[PP CLIENT] Attempting to acknowledge message ${t.messageId}...`),null!==this.authFetch&&void 0!==this.authFetch||jn("[PP CLIENT] Warning: authFetch is undefined! Ensure PeerPayClient is initialized correctly."),$n("[PP CLIENT] authFetch instance:",this.authFetch),$n(`[PP CLIENT] Acknowledgment response: ${await this.acknowledgeMessage({messageIds:[t.messageId]})}`)}catch(t){if(null==t||"object"!=typeof t||!("message"in t)||"string"!=typeof t.message||!t.message.includes("401"))throw zn(`[PP CLIENT] Error acknowledging message: ${t.message}`),t;jn(`[PP CLIENT] Authentication issue while acknowledging: ${t.message}`)}}else{$n("[PP CLIENT] Accepting payment before refunding..."),await this.acceptPayment(t),$n(`[PP CLIENT] Sending refund of ${t.token.amount-1e3} to ${t.sender}...`),await this.sendPayment({recipient:t.sender,amount:t.token.amount-1e3}),$n("[PP CLIENT] Payment successfully rejected and refunded.");try{$n(`[PP CLIENT] Acknowledging message ${t.messageId} after refunding...`),await this.acknowledgeMessage({messageIds:[t.messageId]}),$n("[PP CLIENT] Acknowledgment after refund successful.")}catch(t){zn(`[PP CLIENT] Error acknowledging message after refund: ${t.message}`)}}}async listIncomingPayments(t){return(await this.listMessages({messageBox:this.messageBox,host:t})).map(t=>{const e=Gn(t.body);return{messageId:t.messageId,sender:t.sender,token:e}})}}class Jn{messageBox;constructor(t){this.messageBox=t}async sendMessage(t,e){return(await this.messageBox.sendMessage({recipient:t.recipient,messageBox:t.messageBox,body:t.body},e)).messageId}async sendLiveMessage(t,e){return(await this.messageBox.sendLiveMessage({recipient:t.recipient,messageBox:t.messageBox,body:t.body},e)).messageId}async listMessages(t){const e=await this.messageBox.getIdentityKey();return(await this.messageBox.listMessages({messageBox:t.messageBox,host:t.host})).map(i=>this.toRemittancePeerMessage(i,t.messageBox,e))}async acknowledgeMessage(t){await this.messageBox.acknowledgeMessage({messageIds:t.messageIds})}async listenForLiveMessages(t){const e=await this.messageBox.getIdentityKey();await this.messageBox.listenForLiveMessages({messageBox:t.messageBox,overrideHost:t.overrideHost,onMessage:i=>{t.onMessage(this.toRemittancePeerMessage(i,t.messageBox,e))}})}toRemittancePeerMessage(t,e,i){return{messageId:t.messageId,sender:t.sender,recipient:t.recipient??i,messageBox:t.messageBox??e,body:this.toBodyString(t.body)}}toBodyString(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}}return e})());
|