@bsv/message-box-client 1.1.8 → 1.1.9
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/package.json +4 -4
- package/dist/umd/bundle.js +1 -1
- package/package.json +4 -4
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:()=>Or,PeerPayClient:()=>xr,STANDARD_PAYMENT_MESSAGEBOX:()=>Ar});var i={};t.r(i),t.d(i,{Decoder:()=>br,Encoder:()=>fr,PacketType:()=>lr,protocol:()=>ur});class r{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(r.wordSize);static WORD_MASK=(1n<<r.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&r.WORD_MASK)),e>>=r.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 n=t.length>0?t.length:1;for(let e=n-1;e>=0;e--){const n=void 0===t[e]?0:t[e];i=i<<r.WORD_SIZE_BIGINT|BigInt(n&Number(r.WORD_MASK))}this._magnitude=i,this._sign=e,this._nominalWordLength=n,this.normSign()}get length(){return Math.max(1,this._nominalWordLength)}static isBN(t){return t instanceof r||null!==t&&"object"==typeof t&&t.constructor?.wordSize===r.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,n=i;if("le"!==e&&"be"!==e||(n=e,r=10),"number"!=typeof t)if(Array.isArray(t))this.initArray(t,n);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,s=0;e.startsWith("-")?(i++,s=1):e.startsWith("+")&&i++;const a=e.substring(i);if(0===a.length)return this._initializeState(0n,1===s&&e.startsWith("-")?1:0),void this.normSign();if(16===r){let t;if("le"===n){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),n=parseInt(r,16);if(isNaN(n))throw new Error("Invalid character in "+e);t.push(n)}return this.initArray(t,"le"),this._sign=s,void this.normSign()}try{t=BigInt("0x"+a)}catch(t){throw new Error("Invalid character in "+a)}this._initializeState(t,s),this.normSign()}else try{if(this._parseBaseString(a,r),this._sign=s,this.normSign(),"le"===n){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,n)}_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 n=BigInt(e);for(;r>0n;)i="0123456789abcdefghijklmnopqrstuvwxyz"[Number(r%n)]+i,r/=n;return i}_parseBaseString(t,e){if(0===t.length)return this._magnitude=0n,void this._finishInitialization();this._magnitude=0n;const i=BigInt(e);let n=r.groupSizes[e],s=BigInt(r.groupBases[e]);0!==n&&0n!==s||(n=Math.floor(Math.log(67108863)/Math.log(e)),0===n&&(n=1),s=i**BigInt(n));let a=0;const o=t.length;let c=o%n;if(0===c&&o>0&&(c=n),c>0){const i=t.substring(a,a+c);this._magnitude=BigInt(this._parseBaseWord(i,e)),a+=c}for(;a<o;){const i=t.substring(a,a+n),r=BigInt(this._parseBaseWord(i,e));this._magnitude=this._magnitude*s+r,a+=n}this._finishInitialization()}_parseBaseWord(t,e){let i=0;for(let r=0;r<t.length;r++){const n=t.charCodeAt(r);let s;if(n>=48&&n<=57)s=n-48;else if(n>=65&&n<=90)s=n-65+10;else{if(!(n>=97&&n<=122))throw new Error("Invalid character: "+t[r]);s=n-97+10}if(s>=e)throw new Error("Invalid character");i=i*e+s}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/r.wordSize))}}assert(t,e="Assertion failed"){if(!t)throw new Error(e)}initNumber(t,e="be"){if(this.assert(BigInt(Math.abs(t))<=r.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 r(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=r.groupSizes[t],n=BigInt(r.groupBases[t]);0!==i&&0n!==n||(i=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(t)),0===i&&(i=1),n=BigInt(t)**BigInt(i));let s="",a=this._magnitude;for(;a>0n;){const e=a%n;a/=n;const o=this._bigIntToStringInBase(e,t);if(a>0n){const t=i-o.length;s=t>0&&t<r.zeros.length?r.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>r.MAX_SAFE_INTEGER_BIGINT||t<r.MIN_SAFE_INTEGER_BIGINT)throw new Error("Number can only safely store up to 53 bits");return Number(t)}toJSON(){const t=this._getMinimalHex();return(this.isNeg()?"-":"")+t}toArrayLikeGeneric(t,e){let i=this._magnitude,r=e?0:t.length-1;const n=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+=n}}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 n=new Array(r).fill(0);return 0n===this._magnitude&&r>0?n:0n===this._magnitude&&0===r?[]:(this.toArrayLikeGeneric(n,"le"===t),n)}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 r.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 n=new r(0n);return n._initializeState(i,0),n}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),n=new r(0n);return n._setValueFromSigned(t),n}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 n=this._nominalWordLength;return r&&(n=Math.max(this.length,t.length)),this._magnitude=i,this._finishInitialization(),r&&(this._nominalWordLength=Math.max(this._nominalWordLength,n)),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/r.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 n=Math.floor(t/r.wordSize)+1;return this._nominalWordLength=Math.max(this._nominalWordLength,n),this._finishInitialization(),this.strip()}iadd(t){return this._setValueFromSigned(this._getSignedValue()+t._getSignedValue()),this}add(t){const e=new r(0n);return e._setValueFromSigned(this._getSignedValue()+t._getSignedValue()),e}isub(t){return this._setValueFromSigned(this._getSignedValue()-t._getSignedValue()),this}sub(t){const e=new r(0n);return e._setValueFromSigned(this._getSignedValue()-t._getSignedValue()),e}mul(t){const e=new r(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)<=r.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()*BigInt(t)),this}muln(t){return this.clone().imuln(t)}sqr(){const t=new r(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 r(1n);const e=new r(1n),i=this.clone(),n=t.clone(),s=i.isNeg(),a=n.isOdd();for(s&&i.ineg();!n.isZero();)n.isOdd()&&e.imul(i),i.isqr(),n.iushrn(1);return s&&a&&e.ineg(),e}iushln(t){return this.assert("number"==typeof t&&t>=0),0===t?this:(this._magnitude<<=BigInt(t),this._finishInitialization(),this.strip())}ishln(t){return this.assert(0===this._sign,"ishln requires positive number"),this.iushln(t)}iushrn(t,e,i){if(this.assert("number"==typeof t&&t>=0),0===t)return null!=i&&i._initializeState(0n,0),this;if(null!=i){const e=(1n<<BigInt(t))-1n,r=this._magnitude&e;i._initializeState(r,0)}return this._magnitude>>=BigInt(t),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 n=0===t?1:Math.max(1,Math.ceil(t/r.wordSize));return this._nominalWordLength=n,this._finishInitialization(),this._nominalWordLength=Math.max(this._nominalWordLength,n),this.strip()}maskn(t){return this.clone().imaskn(t)}iaddn(t){return this.assert("number"==typeof t),this.assert(Math.abs(t)<=r.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)<=r.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 r(0n);return{div:"mod"!==e?t:null,mod:"div"!==e?t:null}}const n=this._getSignedValue(),s=t._getSignedValue();let a=null,o=null;"mod"!==e&&(a=n/s),"div"!==e&&(o=n%s,!0===i&&o<0n&&(o+=s<0n?-s:s));const c=null!==a?new r(0n):null;null!==c&&null!==a&&c._setValueFromSigned(a);const h=null!==o?new r(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 n=e/i;const s=e%i;if(0n===s){const t=new r(0n);return t._setValueFromSigned(n),t}2n*(s<0n?-s:s)>=(i<0n?-i:i)&&(e>0n&&i>0n||e<0n&&i<0n?n+=1n:n-=1n);const a=new r(0n);return a._setValueFromSigned(n),a}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)<=r.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,n=1n,s=0n,a=0n,o=1n;for(;0n!==i;){const t=e/i;let r=i;i=e%i,e=r,r=s,s=n-t*s,n=r,r=o,o=a-t*o,a=r}const c=new r(0n);c._setValueFromSigned(n);const h=new r(0n);h._setValueFromSigned(a);const d=new r(0n);return d._initializeState(e<0n?-e:e,0),{a:c,b:h,gcd:d}}gcd(t){let e=this._magnitude,i=t._magnitude;if(0n===e){const t=new r(0n);return t._setValueFromSigned(i),t.iabs()}if(0n===i){const t=new r(0n);return t._setValueFromSigned(e),t.iabs()}for(;0n!==i;){const t=e%i;e=i,i=t}const n=new r(0n);return n._initializeState(e,0),n}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)<=r.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 r(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 r(t,16)}static fromNumber(t){return new r(t)}static fromString(t,e){return new r(t,e)}static fromSm(t,e="big"){if(0===t.length)return new r(0n);let i=0,n="";if("little"===e){const e=t.length-1;let r=t[e];128&r&&(i=1,r&=127),n+=(r<16?"0":"")+r.toString(16);for(let i=e-1;i>=0;i--){const e=t[i];n+=(e<16?"0":"")+e.toString(16)}}else{let e=t[0];128&e&&(i=1,e&=127),n+=(e<16?"0":"")+e.toString(16);for(let e=1;e<t.length;e++){const i=t[e];n+=(i<16?"0":"")+i.toString(16)}}const s=""===n?0n:BigInt("0x"+n),a=new r(0n);return a._initializeState(s,i),a}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)r[i++]=parseInt(e.slice(t,t+2),16);return 1===this._sign?128&r[0]?r.unshift(128):r[0]|=128:128&r[0]&&r.unshift(0),"little"===t?r.reverse():r}static fromBits(t,e=!1){const i=t>>>24,n=8388607&t,s=!!(8388608&t);if(e&&s)throw new Error("negative bit set");if(0===i&&0===n){if(s&&e)throw new Error("negative bit set for zero value");return new r(0n)}const a=new r(n);return i<=3?a.iushrn(8*(3-i)):a.iushln(8*(i-3)),s&&a.ineg(),a}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 n,s=i.length;if(0!==s||e.isZero()||(i=[0],s=1),e.isZero()&&(s=0,i=[]),0===s)n=0;else if(s<=3){n=0;for(let t=0;t<s;t++)n=n<<8|i[t]}else n=i[0]<<16|i[1]<<8|i[2];8388608&n&&s<=255&&(n>>>=8,s++);let a=s<<24|n;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 r(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 r.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");let e=this.umod(t)._magnitude,i=t._magnitude,n=1n,s=0n;const a=t._magnitude;for(;e>1n&&i>1n;){let t=0;for(;0n===(e>>BigInt(t)&1n);)t++;if(t>0){e>>=BigInt(t);for(let e=0;e<t;++e)0n!==(1n&n)&&(n+=a),n>>=1n}let r=0;for(;0n===(i>>BigInt(r)&1n);)r++;if(r>0){i>>=BigInt(r);for(let t=0;t<r;++t)0n!==(1n&s)&&(s+=a),s>>=1n}e>=i?(e-=i,n-=s):(i-=e,s-=n)}let o;if(1n===e)o=n;else if(1n===i)o=s;else if(0n===e&&1n===i)o=s;else{if(0n!==i||1n!==e)throw new Error("_invmp: GCD is not 1, inverse does not exist. aVal="+e+", bVal="+i);o=n}o%=a,o<0n&&(o+=a);const c=new r(0n);return c._initializeState(o,0),c}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 n{name;p;k;n;tmp;constructor(t,e){this.name=t,this.p=new r(e,16),this.n=this.p.bitLength(),this.k=new r(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){const t=new r(BigInt(0)),e=Math.ceil(this.n/r.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 s extends n{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(t,e){const i=4194303,r=t.words,n=t.length,s=Math.min(n,9),a=new Array(s+(n>9?1:0)).fill(0);for(let t=0;t<s;t++)a[t]=r[t];let o=s;if(n<=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 d=new Array(Math.max(1,n-9)).fill(0);let u=0;for(let t=10;t<n;t++){const e=0|r[t];u<d.length&&(d[u++]=(e&i)<<4|c>>>22),c=e}c>>>=22,u<d.length?d[u++]=c:0!==c&&d.length;const l=new Array(u);for(let t=0;t<u;++t)l[t]=d[t];t.words=l}imulK(t){const e=t.words,i=t.length,r=i+2,n=new Array(r).fill(0);for(let t=0;t<i;t++)n[t]=e[t];let s=0;for(let t=0;t<r;t++){const e=0|n[t];s+=977*e,n[t]=67108863&s,s=64*e+(s/67108864|0)}return t.words=n,t}}class a{prime;m;constructor(t){if("k256"===t){const t=new s;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(!(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):(r.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.add(e);return i.cmp(this.m)>=0&&i.isub(this.m),i.forceRed(this)}iadd(t,e){this.verify2(t,e);const i=t.iadd(e);return i.cmp(this.m)>=0&&i.isub(this.m),i}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 r(1)).iushrn(2);return this.pow(t,e)}const i=this.m.subn(1);let n=0;for(;!i.isZero()&&0===i.andln(1);)n++,i.iushrn(1);this.assert(!i.isZero());const s=new r(1).toRed(this),a=s.redNeg(),o=this.m.subn(1).iushrn(1),c=this.m.bitLength(),h=new r(2*c*c).toRed(this);for(;0!==this.pow(h,o).cmp(a);)h.redIAdd(a);let d=this.pow(h,i),u=this.pow(t,i.addn(1).iushrn(1)),l=this.pow(t,i),f=n;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(d,new r(1).iushln(f-e-1));u=u.redMul(i),d=i.redSqr(),l=l.redMul(d),f=e}return u}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(e.isZero())return new r(1).toRed(this);if(0===e.cmpn(1))return t.clone();const i=new Array(16);i[0]=new r(1).toRed(this),i[1]=t;let n=2;for(;n<i.length;n++)i[n]=this.mul(i[n-1],t);let s=i[0],a=0,o=0,c=e.bitLength()%26;for(0===c&&(c=26),n=e.length-1;n>=0;n--){const t=e.words[n];for(let e=c-1;e>=0;e--){const r=t>>e&1;s!==i[0]&&(s=this.sqr(s)),0!==r||0!==a?(a<<=1,a|=r,o++,(4===o||0===n&&0===e)&&(s=this.mul(s,i[a]),o=0,a=0)):o=0}c=26}return s}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 o extends a{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 r(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),n=i.isub(r).iushrn(this.shift);let s=n;return n.cmp(this.m)>=0?s=n.isub(this.m):n.cmpn(0)<0&&(s=n.iadd(this.m)),s.forceRed(this)}mul(t,e){if(t.isZero()||e.isZero())return new r(0).forceRed(this);const i=t.mul(e),n=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),s=i.isub(n).iushrn(this.shift);let a=s;return s.cmp(this.m)>=0?a=s.isub(this.m):s.cmpn(0)<0&&(a=s.iadd(this.m)),a.forceRed(this)}invm(t){return this.imod(t._invmp(this.m).mul(this.r2)).forceRed(this)}}class c{curve;type;precomputed;constructor(t){this.curve=new ht,this.type=t,this.precomputed=null}}class h extends c{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 r(0)):(r.isBN(t)||(t=new r(t,16)),this.x=t,r.isBN(e)||(e=new r(e,16)),this.y=e,r.isBN(i)||(i=new r(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}toP(){if(this.isInfinity())return new ot(null,null);const t=this.z.redInvm(),e=t.redSqr(),i=this.x.redMul(e),r=this.y.redMul(e).redMul(t);return new ot(i,r)}neg(){return new h(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),n=t.x.redMul(i),s=this.y.redMul(e.redMul(t.z)),a=t.y.redMul(i.redMul(this.z)),o=r.redSub(n),c=s.redSub(a);if(0===o.cmpn(0))return 0!==c.cmpn(0)?new h(null,null,null):this.dbl();const d=o.redSqr(),u=d.redMul(o),l=r.redMul(d),f=c.redSqr().redIAdd(u).redISub(l).redISub(l),p=c.redMul(l.redISub(f)).redISub(s.redMul(u)),b=this.z.redMul(t.z).redMul(o);return new h(f,p,b)}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),n=this.y,s=t.y.redMul(e).redMul(this.z),a=i.redSub(r),o=n.redSub(s);if(0===a.cmpn(0))return 0!==o.cmpn(0)?new h(null,null,null):this.dbl();const c=a.redSqr(),d=c.redMul(a),u=i.redMul(c),l=o.redSqr().redIAdd(d).redISub(u).redISub(u),f=o.redMul(u.redISub(l)).redISub(n.redMul(d)),p=this.z.redMul(a);return new h(l,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(),n=this.y.redSqr(),s=n.redSqr();let a=this.x.redAdd(n).redSqr().redISub(r).redISub(s);a=a.redIAdd(a);const o=r.redAdd(r).redIAdd(r),c=o.redSqr().redISub(a).redISub(a);let h=s.redIAdd(s);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(),n=this.y.redSqr(),s=n.redSqr();let a=this.x.redAdd(n).redSqr().redISub(r).redISub(s);a=a.redIAdd(a);const o=r.redAdd(r).redIAdd(r),c=o.redSqr();let h=s.redIAdd(s);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 h(t,e,i)}eq(t){if("affine"===t.type)return this.eq(t.toJ());if(this===t)return!0;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),n=i.redMul(t.z);return 0===this.y.redMul(n).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 n=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(n),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 d=(t,e="Hash assertion failed")=>{if(!t)throw new Error(e)};class u{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=f(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 n=i-0;d(n%4==0);const s=new Array(n/4);for(let e=0,i=0;e<s.length;e++,i+=4){let n;n="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],s[e]=n>>>0}return s}(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()),d(null===this.pending),this._digest()}digestHex(){return this.update(this._pad()),d(null===this.pending),this._digestHex()}_pad(){let t=this.pendingTotal;const e=this._delta8,i=e-(t+this.padLength)%e,r=new Array(i+this.padLength);let n,s;for(r[0]=128,n=1;n<i;n++)r[n]=0;if(t<<=3,"big"===this.endian){for(s=8;s<this.padLength;s++)r[n++]=0;r[n++]=0,r[n++]=0,r[n++]=0,r[n++]=0,r[n++]=t>>>24&255,r[n++]=t>>>16&255,r[n++]=t>>>8&255,r[n++]=255&t}else for(r[n++]=255&t,r[n++]=t>>>8&255,r[n++]=t>>>16&255,r[n++]=t>>>24&255,r[n++]=0,r[n++]=0,r[n++]=0,r[n++]=0,s=8;s<this.padLength;s++)r[n++]=0;return r}}function l(t,e){return 55296==(64512&t.charCodeAt(e))&&!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1))}function f(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 n=t.charCodeAt(r);n<128?i[e++]=n:n<2048?(i[e++]=n>>6|192,i[e++]=63&n|128):l(t,r)?(n=65536+((1023&n)<<10)+(1023&t.charCodeAt(++r)),i[e++]=n>>18|240,i[e++]=n>>12&63|128,i[e++]=n>>6&63|128,i[e++]=63&n|128):(i[e++]=n>>12|224,i[e++]=n>>6&63|128,i[e++]=63&n|128)}}else{(t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+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 p(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function b(t,e){let i="";for(let n=0;n<t.length;n++){let s=t[n];"little"===e&&(s=p(s)),i+=7===(r=s.toString(16)).length?"0"+r:6===r.length?"00"+r:5===r.length?"000"+r:4===r.length?"0000"+r:3===r.length?"00000"+r:2===r.length?"000000"+r:1===r.length?"0000000"+r:r}var r;return i}function g(t,e){const i=new Array(4*t.length);for(let r=0,n=0;r<t.length;r++,n+=4){const s=t[r];"big"===e?(i[n]=s>>>24,i[n+1]=s>>>16&255,i[n+2]=s>>>8&255,i[n+3]=255&s):(i[n+3]=s>>>24,i[n+2]=s>>>16&255,i[n+1]=s>>>8&255,i[n]=255&s)}return i}function m(t,e){return t>>>e|t<<32-e}function y(t,e){return t<<e|t>>>32-e}function w(t,e){return t+e>>>0}function I(t,e,i){return t+e+i>>>0}function k(t,e,i,r){return t+e+i+r>>>0}function v(t,e,i,r,n){return t+e+i+r+n>>>0}function _(t,e,i,r){return 0===t?E(e,i,r):1===t||3===t?function(t,e,i){return t^e^i}(e,i,r):2===t?S(e,i,r):void 0}function E(t,e,i){return t&e^~t&i}function S(t,e,i){return t&e^t&i^e&i}function P(t){return m(t,2)^m(t,13)^m(t,22)}function O(t){return m(t,6)^m(t,11)^m(t,25)}function N(t){return m(t,7)^m(t,18)^t>>>3}const A=[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],x=[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],T=[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],C=[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 R(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 F(t){return t<=15?0:t<=31?1518500249:t<=47?1859775393:t<=63?2400959708:2840853838}function B(t){return t<=15?1352829926:t<=31?1548603684:t<=47?1836072691:t<=63?2053994217:0}class L extends u{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],n=this.h[1],s=this.h[2],a=this.h[3],o=this.h[4],c=r,h=n,d=s,u=a,l=o;for(let f=0;f<80;f++)i=w(y(k(r,R(f,n,s,a),t[A[f]+e],F(f)),T[f]),o),r=o,o=a,a=y(s,10),s=n,n=i,i=w(y(k(c,R(79-f,h,d,u),t[x[f]+e],B(f)),C[f]),l),c=l,l=u,u=y(d,10),d=h,h=i;i=I(this.h[1],s,u),this.h[1]=I(this.h[2],a,l),this.h[2]=I(this.h[3],o,c),this.h[3]=I(this.h[4],r,h),this.h[4]=I(this.h[0],n,d),this.h[0]=i}_digest(){return g(this.h,"little")}_digestHex(){return b(this.h,"little")}}class D extends u{h;W;k;constructor(){super(512,256,192,64),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=[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],this.W=new Array(64)}_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]=k(m(n=i[r-2],17)^m(n,19)^n>>>10,i[r-7],N(i[r-15]),i[r-16]);var n;let s=this.h[0],a=this.h[1],o=this.h[2],c=this.h[3],h=this.h[4],u=this.h[5],l=this.h[6],f=this.h[7];for(d(this.k.length===i.length),r=0;r<i.length;r++){const t=v(f,O(h),E(h,u,l),this.k[r],i[r]),e=w(P(s),S(s,a,o));f=l,l=u,u=h,h=w(c,t),c=o,o=a,a=s,s=w(t,e)}this.h[0]=w(this.h[0],s),this.h[1]=w(this.h[1],a),this.h[2]=w(this.h[2],o),this.h[3]=w(this.h[3],c),this.h[4]=w(this.h[4],h),this.h[5]=w(this.h[5],u),this.h[6]=w(this.h[6],l),this.h[7]=w(this.h[7],f)}_digest(){return g(this.h,"big")}_digestHex(){return b(this.h,"big")}}class M extends u{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]=y(i[r-3]^i[r-8]^i[r-14]^i[r-16],1);let n=this.h[0],s=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=v(y(n,5),_(t,s,a,o),c,i[r],this.k[t]);c=o,o=a,a=y(s,30),s=n,n=e}this.h[0]=w(this.h[0],n),this.h[1]=w(this.h[1],s),this.h[2]=w(this.h[2],a),this.h[3]=w(this.h[3],o),this.h[4]=w(this.h[4],c)}_digest(){return g(this.h,"big")}_digestHex(){return b(this.h,"big")}}class V{inner;outer;blockSize=64;outSize=32;constructor(t){let e;for((t=f(t,"hex")).length>this.blockSize&&(t=(new D).update(t).digest()),d(t.length<=this.blockSize),e=t.length;e<this.blockSize;e++)t.push(0);for(e=0;e<t.length;e++)t[e]^=54;for(this.inner=(new D).update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=(new D).update(t)}update(t,e){return this.inner.update(t,e),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}const q=(t,e)=>(new D).update(t,e).digest(),H=(t,e)=>{const i=(new D).update(t,e).digest();return(new D).update(i).digest()},U=(t,e)=>{const i=(new D).update(t,e).digest();return(new L).update(i).digest()},K=(t,e,i)=>new V(t).update(e,i).digest(),$=t=>{let e="";for(const r of t)e+=(i=r.toString(16)).length%2==1?"0"+i:i;var i;return e},W=(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 z(t);case"base64":return j(t);default:return function(t){const e=[];for(let i=0;i<t.length;i++){const r=t.codePointAt(i);if(void 0===r)throw new Error(`Index out of range: ${i}`);let n=r;n>65535?i++:n>=55296&&n<=57343&&(n=65533),n<=127?e.push(n):n<=2047?e.push(192|n>>6,128|63&n):n<=65535?e.push(224|n>>12,128|n>>6&63,128|63&n):e.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}return e}(t)}},z=t=>{(t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t);const e=[];for(let i=0;i<t.length;i+=2)e.push(parseInt(t[i]+t[i+1],16));return e},j=t=>{const e=[];let i=0,r=0;for(const n of t.replace(/=+$/,""))i=i<<6|"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(n),r+=6,r>=8&&(r-=8,e.push(i>>r&255),i&=(1<<r)-1);return e},X=t=>{let e="",i=0;for(let r=0;r<t.length;r++){const n=t[r];if(i>0)i--;else if(n<=127)e+=String.fromCharCode(n);else if(n>=192&&n<=223){i=1;const s=(31&n)<<6|63&t[r+1];e+=String.fromCharCode(s)}else if(n>=224&&n<=239){i=2;const s=(15&n)<<12|(63&t[r+1])<<6|63&t[r+2];e+=String.fromCharCode(s)}else if(n>=240&&n<=247){i=3;const s=(7&n)<<18|(63&t[r+1])<<12|(63&t[r+2])<<6|63&t[r+3],a=55296+(s-65536>>10),o=56320+(s-65536&1023);e+=String.fromCharCode(a,o)}}return e},G=(t,e)=>{switch(e){case"hex":return $(t);case"utf8":return X(t);default:return t}};function J(t){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let i,r="";for(i=0;i<t.length;i+=3){const n=t[i],s=i+1<t.length?t[i+1]:0,a=i+2<t.length?t[i+2]:0,o=(3&n)<<4|s>>4,c=(15&s)<<2|a>>6,h=63&a;r+=e.charAt(n>>2)+e.charAt(o),r+=i+1<t.length?e.charAt(c):"=",r+=i+2<t.length?e.charAt(h):"="}return r}const Y="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Z=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,n=(t.length-r)*(Math.log(58)/Math.log(256))+1>>>0,s=new Uint8Array([...new Uint8Array(r),...(t.match(/./gmu)??[]).map((t=>Y.indexOf(t))).reduce(((t,e)=>t.map((t=>{const i=58*t+e;return e=i>>8,i}))),new Uint8Array(n)).reverse().filter((a=!1,t=>a=a||t))]);var a;return[...s]},Q=t=>{const e=Array(256).fill(-1);for(let t=0;t<58;++t)e[Y.charCodeAt(t)]=t;const i=[];for(const r of t){let t=r;for(let r=0;r<i.length;++r){const n=(e[i[r]]<<8)+t;i[r]=Y.charCodeAt(n%58),t=n/58|0}for(;0!==t;)i.push(Y.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)},tt=(t,e=[0])=>{let i=H([...e,...t]);return i=[...e,...t,...i.slice(0,4)],Q(i)},et=(t,e,i=1)=>{const r=Z(t);let n=r.slice(0,i),s=r.slice(i,-4),a=[...n,...s];return a=H(a),r.slice(-4).forEach(((t,e)=>{if(t!==a[e])throw new Error("Invalid checksum")})),"hex"===e&&(n=$(n),s=$(s)),{prefix:n,data:s}};class it{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}toArray(){const t=this.length,e=new Array(t);let i=0;for(const t of this.bufs)for(const r of t)e[i++]=r;return e}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.bufs.push(e),this.length+=e.length,this}writeUInt8(t){const e=new Array(1);return e[0]=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.bufs.push(e),this.length+=2,this}writeInt16BE(t){return this.writeUInt16BE(65535&t)}writeUInt16LE(t){const e=[255&t,t>>8&255];return this.bufs.push(e),this.length+=2,this}writeInt16LE(t){return this.writeUInt16LE(65535&t)}writeUInt32BE(t){const e=[t>>24&255,t>>16&255,t>>8&255,255&t];return this.bufs.push(e),this.length+=4,this}writeInt32BE(t){return this.writeUInt32BE(t>>>0)}writeUInt32LE(t){const e=[255&t,t>>8&255,t>>16&255,t>>24&255];return this.bufs.push(e),this.length+=4,this}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){const e=new r(t).toArray("be",8);return this.writeReverse(e),this}writeVarIntNum(t){const e=it.varIntNum(t);return this.write(e),this}writeVarIntBn(t){const e=it.varIntBn(t);return this.write(e),this}static varIntNum(t){let e;if(t<0)return this.varIntBn(new r(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(at)),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 r(4294967296))){const i=t.toNumber();e=[254,255&i,i>>8&255,i>>16&255,i>>24&255]}else{const i=new it;i.writeUInt8(255),i.writeUInt64LEBn(t),e=i.toArray()}return e}}class rt{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 r(t);return this.pos=this.pos+8,e}readUInt64LEBn(){const t=this.readReverse(8);return new r(t)}readInt64LEBn(){const t=this.readReverse(8);let e=new r(t);return e.gte(st)&&(e=e.sub(at)),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 r(2).pow(new r(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 r(this.readUInt16LE());case 254:return new r(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new r(t)}}}const nt=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[]},st=new r(2).pow(new r(63)),at=new r(2).pow(new r(64));class ot extends c{static red=new a("k256");static a=new r(0).toRed(ot.red);static b=new r(7).toRed(ot.red);static zero=new r(0).toRed(ot.red);x;y;inf;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");return new ot(t.slice(1,33),t.slice(33,65))}if((2===t[0]||3===t[0])&&t.length-1==32)return ot.fromX(t.slice(1,33),3===t[0]);throw new Error("Unknown point format")}static fromString(t){const e=W(t,"hex");return ot.fromDER(e)}static redSqrtOptimized(t){const e=ot.red.m.addn(1).iushrn(2);return t.redPow(e)}static fromX(t,e){if("function"==typeof BigInt){function i(t,e){return(t%e+e)%e}function n(t,e,r){let n=BigInt(1);for(t=i(t,r);e>BigInt(0);)(e&BigInt(1))===BigInt(1)&&(n=i(n*t,r)),e>>=BigInt(1),t=i(t*t,r);return n}function s(t,e){const r=n(t,e+BigInt(1)>>BigInt(2),e);return i(r*r,e)===i(t,e)?r:null}const o=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),c=BigInt(7);let h;if(t instanceof r)h=BigInt("0x"+t.toString(16));else if("string"==typeof t)h=BigInt("0x"+t);else if(Array.isArray(t))h=BigInt("0x"+$(t).padStart(64,"0"));else{if("number"!=typeof t)throw new Error("Invalid x-coordinate type");h=BigInt(t)}h=i(h,o);let d=s(i(n(h,BigInt(3),o)+c,o),o);if(null===d)throw new Error("Invalid point");const u=d%BigInt(2)===BigInt(1);(e&&!u||!e&&u)&&(d=o-d);const l=new r(h.toString(16),16),f=new r(d.toString(16),16);return new ot(l,f)}{const p=new a("k256"),b=new r(0).toRed(p),g=new r(7).toRed(p),m=new r(0).toRed(p);r.isBN(t)||(t=new r(t,16)),null==t.red&&(t=t.toRed(p));const y=t.redSqr().redMul(t).redIAdd(t.redMul(b)).redIAdd(g);let w=y.redSqrt();if(0!==w.redSqr().redSub(y).cmp(m))throw new Error("invalid point");const I=w.fromRed().isOdd();return(e&&!I||!e&&I)&&(w=w.redNeg()),new ot(t,w)}}static fromJSON(t,e){"string"==typeof t&&(t=JSON.parse(t));const i=new ot(t[0],t[1],e);if("object"!=typeof t[2])return i;const r=t=>new ot(t[0],t[1],e),n=t[2];return i.precomputed={beta:null,doubles:"object"==typeof n.doubles&&null!==n.doubles?{step:n.doubles.step,points:[i].concat(n.doubles.points.map(r))}:void 0,naf:"object"==typeof n.naf&&null!==n.naf?{wnd:n.naf.wnd,points:[i].concat(n.naf.points.map(r))}: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):(r.isBN(t)||(t=new r(t,16)),this.x=t,r.isBN(e)||(e=new r(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(){return this.curve.validate(this)}encode(t=!0,e){const i=this.curve.p.byteLength(),r=this.getX().toArray("be",i);let n;return n=t?[this.getY().isEven()?2:3].concat(r):[4].concat(r,this.getY().toArray("be",i)),"hex"!==e?n:$(n)}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 ot(new r(0),new r(0));if(0===this.x?.cmp(t.x??new r(0)))return new ot(new r(0),new r(0));let e=this.y?.redSub(t.y??new r(0))??new r(0);0!==e.cmpn(0)&&(e=e.redMul(this.x?.redSub(t.x??new r(0)).redInvm()??new r(1)));const i=e?.redSqr().redISub(this.x??new r(0)).redISub(t.x??new r(0)),n=(e??new r(1)).redMul((this.x??new r(0)).redSub(i??new r(0))).redISub(this.y??new r(0));return new ot(i??new r(0),n??new r(0))}dbl(){if(this.inf)return this;const t=(this.y??new r(0)).redAdd(this.y??new r(0));if(0===t.cmpn(0))return new ot(new r(0),new r(0));const e=this.curve.a,i=(this.x??new r(0)).redSqr(),n=t.redInvm(),s=i.redAdd(i).redIAdd(i).redIAdd(e).redMul(n),a=s.redSqr().redISub((this.x??new r(0)).redAdd(this.x??new r(0))),o=s.redMul((this.x??new r(0)).redSub(a)).redISub(this.y??new r(0));return new ot(a,o)}getX(){return(this.x??new r(0)).fromRed()}getY(){return(this.y??new r(0)).fromRed()}mul(t){return r.isBN(t)||(t=new r(t,16)),this.isInfinity()?this:this._hasDoubles(t)?this._fixedNafMul(t):this._endoWnafMulAdd([this],[t])}mulAdd(t,e,i){const r=[this,e],n=[t,i];return this._endoWnafMulAdd(r,n)}jmulAdd(t,e,i){const r=[this,e],n=[t,i];return this._endoWnafMulAdd(r,n,!0)}eq(t){return this===t||this.inf===t.inf&&(this.inf||0===(this.x??new r(0)).cmp(t.x??new r(0))&&0===(this.y??new r(0)).cmp(t.y??new r(0)))}neg(t){if(this.inf)return this;const e=new ot(this.x,(this.y??new r(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 h(null,null,null):new h(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 ot((this.x??new r(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 ot(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 n=[];for(let t=0;t<i.length;t+=e.step){let r=0;for(let n=t+e.step-1;n>=t;n--)r=(r<<1)+i[n];n.push(r)}let s=new h(null,null,null),a=new h(null,null,null);for(let t=r;t>0;t--){for(let i=0;i<n.length;i++){const r=n[i];r===t?a=a.mixedAdd(e.points[i]):r===-t&&(a=a.mixedAdd(e.points[i].neg()))}s=s.add(a)}return s.toP()}_wnafMulAdd(t,e,i,n,s){const a=this.curve._wnafT1.map((t=>t.toNumber())),o=this.curve._wnafT2.map((()=>[])),c=this.curve._wnafT3.map((()=>[]));let d=0;for(let i=0;i<n;i++){const r=e[i]._getNAFPoints(t);a[i]=r.wnd,o[i]=r.points}for(let t=n-1;t>=1;t-=2){const n=t-1,s=t;if(1!==a[n]||1!==a[s]){c[n]=this.curve.getNAF(i[n],a[n],this.curve._bitLength),c[s]=this.curve.getNAF(i[s],a[s],this.curve._bitLength),d=Math.max(c[n].length,d),d=Math.max(c[s].length,d);continue}const h=[e[n],null,null,e[s]];0===(e[n].y??new r(0)).cmp(e[s].y??new r(0))?(h[1]=e[n].add(e[s]),h[2]=e[n].toJ().mixedAdd(e[s].neg())):0===(e[n].y??new r(0)).cmp((e[s].y??new r(0)).redNeg())?(h[1]=e[n].toJ().mixedAdd(e[s]),h[2]=e[n].add(e[s].neg())):(h[1]=e[n].toJ().mixedAdd(e[s]),h[2]=e[n].toJ().mixedAdd(e[s].neg()));const u=[-3,-1,-5,-7,0,7,5,1,3],l=this.curve.getJSF(i[n],i[s]);d=Math.max(l[0].length,d),c[n]=new Array(d),c[s]=new Array(d);for(let t=0;t<d;t++){const e=0|l[0][t],i=0|l[1][t];c[n][t]=u[3*(e+1)+(i+1)],c[s][t]=0,o[n]=h}}let u=new h(null,null,null);const l=this.curve._wnafT4;for(let t=d;t>=0;t--){let e=0;for(;t>=0;){let i=!0;for(let e=0;e<n;e++)l[e]=new r("number"==typeof c[e][t]?c[e][t]:0),l[e].isZero()||(i=!1);if(!i)break;e++,t--}if(t>=0&&e++,u=u.dblp(e),t<0)break;const i=new r(1),s=new r(2);for(let t=0;t<n;t++){const e=l[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<n;t++)o[t]=[];return!0===s?u:u.toP()}_endoWnafMulAdd(t,e,i){const n=new Array(2*t.length),s=new Array(2*t.length);let a;for(a=0;a<t.length;a++){const i=this.curve._endoSplit(e[a]);let o=t[a],c=o._getBeta()??new ot(new r(0),new r(0));0!==i.k1.negative&&(i.k1.ineg(),o=o.neg(!0)),0!==i.k2.negative&&(i.k2.ineg(),c=c.neg(!0)),n[2*a]=o,n[2*a+1]=c,s[2*a]=i.k1,s[2*a+1]=i.k2}const o=this._wnafMulAdd(1,n,s,2*a,i);for(let t=0;t<2*a;t++)n[t]=null,s[t]=null;return o}_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 n=0;n<(e??0);n+=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 ct;class ht{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 n=1<<e+1,s=t.clone();for(let t=0;t<r.length;t++){let e;const i=s.andln(n-1);s.isOdd()?(e=i>(n>>1)-1?(n>>1)-i:i,s.isubn(e)):e=0,r[t]=e,s.iushrn(1)}return r}getJSF(t,e){const i=[[],[]];t=t.clone(),e=e.clone();let r=0,n=0;for(;t.cmpn(-r)>0||e.cmpn(-n)>0;){let s,a,o=t.andln(3)+r&3,c=e.andln(3)+n&3;if(3===o&&(o=-1),3===c&&(c=-1),1&o){const e=t.andln(7)+r&7;s=3!==e&&5!==e||2!==c?o:-o}else s=0;if(i[0].push(s),1&c){const t=e.andln(7)+n&7;a=3!==t&&5!==t||2!==o?c:-c}else a=0;i[1].push(a),2*r===s+1&&(r=1-r),2*n===a+1&&(n=1-n),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?W(t,"hex"):t}static intFromLE(t){return new r(t,"hex","le")}constructor(){if(void 0!==ct)return ct;ct=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 r(t.p,16),this.red=new a(t.prime),this.zero=new r(0).toRed(this.red),this.one=new r(1).toRed(this.red),this.two=new r(2).toRed(this.red),this.n=new r(t.n,16),this.g=ot.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 r(t.a,16).toRed(this.red),this.b=new r(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,n;if(void 0!==t.beta)e=new r(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 r(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,n=null!=this.g.x?this.g.x.redMul(e):void 0;if(null!=r&&null!=n&&0===r.cmp(n))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,n=null!=this.g.x?this.g.x.redMul(e):void 0;if(null==r||null==n)throw new Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");ht.assert(0===r.cmp(n),"Lambda selection does not match computed beta.")}}return n="object"==typeof t.basis&&null!==t.basis?t.basis.map((function(t){return{a:new r(t.a,16),b:new r(t.b,16)}})):this._getEndoBasis(i),{beta:e,lambda:i,basis:n}}_getEndoRoots(t){const e=t===this.p?this.red:new o(t),i=new r(2).toRed(e).redInvm(),n=i.redNeg(),s=new r(3).toRed(e).redNeg().redSqrt().redMul(i);return[n.redAdd(s).fromRed(),n.redSub(s).fromRed()]}_getEndoBasis(t){const e=this.n.ushrn(Math.floor(this.n.bitLength()/2));let i,n,s,a,o,c,h=t,d=this.n.clone(),u=new r(1),l=new r(0),f=new r(0),p=new r(1),b=new r(0),g=0,m=new r(0),y=new r(0);for(;0!==h.cmpn(0);){const t=d.div(h);m=d.sub(t.mul(h)),y=f.sub(t.mul(u));const r=p.sub(t.mul(l));if(void 0===s&&m.cmp(e)<0)i=b.neg(),n=u,s=m.neg(),a=y;else if(void 0!==s&&2==++g)break;b=m,d=h,h=m,f=u,u=y,p=l,l=r}if(void 0===i||void 0===n||void 0===s||void 0===a)throw new Error("Failed to compute Endo Basis values");o=m.neg(),c=y;const w=s.sqr().add(a.sqr());return o.sqr().add(c.sqr()).cmp(w)>=0&&(o=i,c=n),0!==s.negative&&(s=s.neg(),a=a.neg()),0!==o.negative&&(o=o.neg(),c=c.neg()),[{a:s,b:a},{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],n=r.b.mul(t).divRound(this.n),s=i.b.neg().mul(t).divRound(this.n),a=n.mul(i.a),o=s.mul(r.a),c=n.mul(i.b),h=s.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),n=e.redSqr().redMul(e).redIAdd(r).redIAdd(this.b);return 0===i.redSqr().redISub(n).cmpn(0)}}class dt{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=W(t,e);const n=new class{place;constructor(){this.place=0}};if(48!==t[n.place++])throw new Error("Signature DER must start with 0x30");if(i(t,n)+n.place!==t.length)throw new Error("Signature DER invalid");if(2!==t[n.place++])throw new Error("Signature DER invalid");const s=i(t,n);let a=t.slice(n.place,s+n.place);if(n.place+=s,2!==t[n.place++])throw new Error("Signature DER invalid");const o=i(t,n);if(t.length!==o+n.place)throw new Error("Invalid R-length in signature DER");let c=t.slice(n.place,o+n.place);if(0===a[0]){if(!(128&a[1]))throw new Error("Invalid R-value in signature DER");a=a.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 dt(new r(a),new r(c))}static fromCompact(t,e){if(65!==(t=W(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 dt(new r(t.slice(1,33)),new r(t.slice(33,65)))}constructor(t,e){this.r=t,this.s=e}verify(t,e,i){const n=new r(q(t,i),16);return pt(n,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(),n=this.s.toArray();for(128&r[0]&&(r=[0].concat(r)),128&n[0]&&(n=[0].concat(n)),r=i(r),n=i(n);0===n[0]&&!(128&n[1]);)n=n.slice(1);let s=[2];e(s,r.length),s=s.concat(r),s.push(2),e(s,n.length);const a=s.concat(n);let o=[48];return e(o,a.length),o=o.concat(a),"hex"===t?$(o):"base64"===t?J(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 n=[r];return n=n.concat(this.r.toArray("be",32)),n=n.concat(this.s.toArray("be",32)),"hex"===i?$(n):"base64"===i?J(n):n}RecoverPublicKey(t,e){const i=this.r,r=this.s,n=!!(1&t),s=t>>1,a=new ht,o=a.n,c=a.g,h=0!==s?i.add(o):i,d=ot.fromX(h,n);if(!d.mul(o).isInfinity())throw new Error("nR is not at infinity");const u=e.neg().umod(o),l=i.invm(o),f=l.mul(r).umod(o),p=l.mul(u).umod(o),b=c.mul(p).add(d.mul(f)),g=new bt(b);return g.validate(),g}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 ut{K;V;constructor(t,e){if(t=W(t,"hex"),e=W(e,"hex"),t.length<32)throw new Error("Not enough entropy. Minimum is 256 bits");const i=t.concat(e);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(i)}hmac(){return new V(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(),$(i)}}function lt(t,e,i=new ht){const r=8*t.byteLength()-i.n.bitLength();return r>0&&t.iushrn(r),null===e&&t.cmp(i.n)>=0?t.sub(i.n):t}const ft=(t,e,i=!1,n)=>{if("function"==typeof BigInt){const s=BigInt(0),a=BigInt(1),o=BigInt(2),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),h=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),d={x:BigInt("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"),y:BigInt("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")},u=BigInt("0x"+t.toString(16)),l=BigInt("0x"+e.toString(16));if(l<=s||l>=c)throw new Error("Invalid private key");function f(t,e){const i=t.toString(16).padStart(2*e,"0"),r=new Uint8Array(e);for(let t=0;t<e;t++)r[t]=parseInt(i.substr(2*t,2),16);return r}const p=32,b=f(l,p),g=f(u,p),m=new ut(Array.from(b),Array.from(g)),y=c-a;let w=0;function I(t,e,i=!0){const r=t.toString(2).length-e.toString(2).length;return r>0&&(t>>=BigInt(r)),!i&&t>=e?t-e:t}function k(t){if("function"==typeof t){const e=t(w).toString(16);return BigInt("0x"+e)}if(null!=t&&r.isBN(t)){const e=t.toString(16);return BigInt("0x"+e)}{const t=m.generate(p);return BigInt("0x"+t)}}function v(t,e){return(t%e+e)%e}function _(t,e){let i=a,r=s,n=v(t,e),o=e;for(;n>a;){const t=o/n,e=r-i*t,s=o-n*t;r=i,i=e,o=n,n=s}return v(i,e)}function E(t,e){if(null===t)return e;if(null===e)return t;if(t.x===e.x&&t.y===v(-e.y,h))return null;let i;if(t.x===e.x&&t.y===e.y){if(t.y===s)return null;const e=v(BigInt(3)*t.x*t.x,h);i=v(e*_(o*t.y,h),h)}else{const r=v(e.y-t.y,h);i=v(r*_(e.x-t.x,h),h)}const r=v(i*i-t.x-e.x,h);return{x:r,y:v(i*(t.x-r)-t.y,h)}}function S(t,e){let i=e,r=null;for(;t>BigInt(0);)t%BigInt(2)===BigInt(1)&&(r=null===r?i:E(r,i)??r),i=E(i,i)??i,t>>=BigInt(1);if(null===r)throw new Error("Scalar multiplication resulted in an invalid point.");return r}let P=!1;for(;!P;){w+=1,P=!0,w+=1;let O=k(n);if(O=I(O,c,!0),O<=a||O>=y){if(n instanceof r)throw new Error("Invalid fixed custom K value (must be more than 1 and less than N-1)");continue}const N=S(O,d);if(null===N){if(n instanceof r)throw new Error("Invalid fixed custom K value (must not create a point at infinity when multiplied by the generator point)");continue}const A=v(N.x,c);if(A===s){if(n instanceof r)throw new Error("Invalid fixed custom K value (when multiplied by G, the resulting x coordinate mod N must not be zero)");continue}const x=_(O,c),T=v(A*l,c);let C=v(x*(u+T),c);if(C===s){if(n instanceof r)throw new Error("Invalid fixed custom K value (when used with the key, it cannot create a zero value for S)");continue}i&&C>c/o&&(C=c-C);const R=new r(A.toString(16),16),F=new r(C.toString(16),16);return new dt(R,F)}}else{const B=new ht;t=lt(t);const L=B.n.byteLength(),D=e.toArray("be",L),M=t.toArray("be",L),V=new ut(D,M),q=B.n.subn(1);for(let H=0;;H++){let U="function"==typeof n?n(H):r.isBN(n)?n:new r(V.generate(L),16);if(null==U)throw new Error("k is undefined");if(U=lt(U,!0),U.cmpn(1)<=0||U.cmp(q)>=0){if(r.isBN(n))throw new Error("Invalid fixed custom K value (must be more than 1 and less than N-1)");continue}const K=B.g.mul(U);if(K.isInfinity()){if(r.isBN(n))throw new Error("Invalid fixed custom K value (must not create a point at infinity when multiplied by the generator point)");continue}const $=K.getX().umod(B.n);if(0===$.cmpn(0)){if(r.isBN(n))throw new Error("Invalid fixed custom K value (when multiplied by G, the resulting x coordinate mod N must not be zero)");continue}let W=U.invm(B.n).mul($.mul(e).iadd(t));if(W=W.umod(B.n),0!==W.cmpn(0))return i&&W.cmp(B.n.ushrn(1))>0&&(W=B.n.sub(W)),new dt($,W);if(r.isBN(n))throw new Error("Invalid fixed custom K value (when used with the key, it cannot create a zero value for S)")}}throw new Error("Failed to generate a valid signature")},pt=(t,e,i)=>{if("function"==typeof BigInt){const r=BigInt(0),n=BigInt(1),s=BigInt(2),a=BigInt(3),o=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),h={x:BigInt("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"),y:BigInt("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")},d=(t,e)=>(t%e+e)%e,u=(t,e)=>{let[i,s]=[t,e],[a,o]=[BigInt(1),BigInt(0)];for(;s!==r;){const t=i/s;[i,s]=[s,i-t*s],[a,o]=[o,a-t*o]}return i>n?r:d(a,e)},l=(t,e,i)=>d(t*e,i),f=(t,e,i)=>d(t-e,i),p=BigInt(4),b=BigInt(8),g=t=>{const{X:e,Y:i,Z:c}=t;if(i===r)return{X:r,Y:n,Z:r};const h=l(i,i,o),d=l(p,l(e,h,o),o),u=l(a,l(e,e,o),o),g=f(l(u,u,o),l(s,d,o),o);return{X:g,Y:f(l(u,f(d,g,o),o),l(b,l(h,h,o),o),o),Z:l(s,l(i,c,o),o)}},m=(t,e)=>{if(t.Z===r)return e;if(e.Z===r)return t;const i=l(t.Z,t.Z,o),a=l(e.Z,e.Z,o),c=l(t.X,a,o),h=l(e.X,i,o),d=l(t.Y,l(a,e.Z,o),o),u=l(e.Y,l(i,t.Z,o),o),p=f(h,c,o),b=f(u,d,o);if(p===r)return b===r?g(t):{X:r,Y:n,Z:r};const m=l(p,p,o),y=l(p,m,o),w=l(c,m,o),I=f(f(l(b,b,o),y,o),l(s,w,o),o);return{X:I,Y:f(l(b,f(w,I,o),o),l(d,y,o),o),Z:l(p,l(t.Z,e.Z,o),o)}},y=(t,e)=>{const i={X:e.x,Y:e.y,Z:n};let s={X:r,Y:n,Z:r};const a=t.toString(2);for(let t=0;t<a.length;t++)s=g(s),"1"===a[t]&&(s=m(s,i));return s},w=(t,e,i)=>{const{r:n,s}=i,a=t;if(n<=r||n>=c||s<=r||s>=c)return!1;const f=u(s,c);if(f===r)return!1;const p=l(a,f,c),b=l(n,f,c),g=y(p,h),w=y(b,e),I=m(g,w);if(I.Z===r)return!1;const k=u(I.Z,o);if(k===r)return!1;const v=l(k,k,o),_=l(I.X,v,o);return d(_,c)===n},I=BigInt("0x"+t.toString(16));if(null==i.x||null==i.y)throw new Error("Invalid public key: missing coordinates.");return w(I,{x:BigInt("0x"+i.x.toString(16)),y:BigInt("0x"+i.y.toString(16))},{r:BigInt("0x"+e.r.toString(16)),s:BigInt("0x"+e.s.toString(16))})}{const r=new ht;t=lt(t);const n=e.r,s=e.s;if(n.cmpn(1)<0||n.cmp(r.n)>=0)return!1;if(s.cmpn(1)<0||s.cmp(r.n)>=0)return!1;const a=s.invm(r.n),o=a.mul(t).umod(r.n),c=a.mul(n).umod(r.n),h=r.g.jmulAdd(o,i,c);return!h.isInfinity()&&h.eqXToP(n)}};class bt extends ot{static fromPrivateKey(t){const e=(new ht).g.mul(t);return new bt(e.x,e.y)}static fromString(t){const e=ot.fromString(t);return new bt(e.x,e.y)}static fromDER(t){const e=ot.fromDER(t);return new bt(e.x,e.y)}constructor(t,e=null,i=!0){if(t instanceof ot)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.mul(t)}verify(t,e,i){const n=new r(q(t,i),16);return pt(n,e,this)}toDER(t){return"hex"===t?this.encode(!0,t):this.encode(!0)}toHash(t){const e=U(this.encode(!0));return"hex"===t?$(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 tt(this.toHash(),t)}deriveChild(t,e){const i=this.deriveSharedSecret(t),n=W(e,"utf8"),s=K(i.encode(!0),n),a=(new ht).g.mul(new r(s)),o=this.add(a);return new bt(o.x,o.y)}static fromMsgHashAndCompactSignature(t,e,i){const n=W(e,i);if(65!==n.length)throw new Error("Invalid Compact Signature");const s=n[0];if(s<27||s>=35)throw new Error("Invalid Compact Byte");let a=n[0]-27;return a>3&&(a-=4),new dt(new r(n.slice(1,33)),new r(n.slice(33,65))).RecoverPublicKey(a,t)}}class gt{_rand;constructor(){const t=()=>{throw new Error("No secure random number generator is available in this environment.")};if(this._rand=t,"object"==typeof self)self.crypto?.getRandomValues?this._rand=t=>{const e=new Uint8Array(t);return self.crypto.getRandomValues(e),[...e]}:this._rand=t;else try{const t=require("crypto");"function"==typeof t.randomBytes&&(this._rand=e=>[...t.randomBytes(e)])}catch{this._rand=t}}generate(t){return this._rand(t)}}let mt=null;const yt=t=>(null==mt&&(mt=new gt),mt.generate(t));class wt{x;y;constructor(t,e){const i=(new ht).p;this.x=t.umod(i),this.y=e.umod(i)}toString(){return Q(this.x.toArray())+"."+Q(this.y.toArray())}static fromString(t){const[e,i]=t.split(".");return new wt(new r(Z(e)),new r(Z(i)))}}class It{points;threshold;constructor(t,e){this.points=t,this.threshold=e??t.length}static fromPrivateKey(t,e){const i=(new ht).p,n=[new wt(new r(0),new r(t.toArray()))];for(let t=1;t<e;t++){const t=new r(yt(32)).umod(i),e=new r(yt(32)).umod(i);n.push(new wt(t,e))}return new It(n)}valueAt(t){const e=(new ht).p;let i=new r(0);for(let r=0;r<this.threshold;r++){let n=this.points[r].y;for(let i=0;i<this.threshold;i++)if(r!==i){const s=this.points[i].x,a=this.points[r].x,o=t.sub(s).umod(e),c=a.sub(s).umod(e).invm(e),h=o.mul(c).umod(e);n=n.mul(h).umod(e)}i=i.add(n).umod(e)}return i}}class kt{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 n=t.split(".");if(4!==n.length)throw new Error("Invalid share format in share "+r.toString()+'. Expected format: "x.y.t.i" - received '+t);const[s,a,o,c]=n;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,wt.fromString([s,a].join("."))}));return new kt(r,e,i)}toBackupFormat(){return this.points.map((t=>t.toString()+"."+this.threshold.toString()+"."+this.integrity))}}class vt extends r{static fromRandom(){return new vt(yt(32))}static fromString(t,e="hex"){return new vt(super.fromString(t,e).toArray())}static fromHex(t){return new vt(super.fromHex(t,"big"))}static fromWif(t,e=1){const i=et(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 vt(i.data.slice(0,32))}constructor(t=0,e=10,i="be",n="apply"){if(t instanceof r?(super(),t.copy(this)):super(t,e,i),"nocheck"!==n){const t=this.checkInField();if(!t.inField){if("error"===n)throw new Error("Input is out of field");r.move(this,t.modN)}}}checkInField(){const t=new ht,e=this.mod(t.n);return{inField:0===this.cmp(e),modN:e}}isValid(){return this.checkInField().inField}sign(t,e,i=!0,n){const s=new r(q(t,e),16);return ft(s,this,i,n)}verify(t,e,i){const n=new r(q(t,i),16);return pt(n,e,this.toPublicKey())}toPublicKey(){const t=(new ht).g.mul(this);return new bt(t.x,t.y)}toWif(t=[128]){if(!this.isValid())throw new Error("Value is out of field");return tt([...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.mul(this)}deriveChild(t,e){const i=this.deriveSharedSecret(t),n=W(e,"utf8"),s=K(i.encode(!0),n),a=new ht;return new vt(this.add(new r(s)).mod(a.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=It.fromPrivateKey(this,t),n=[];for(let t=0;t<e;t++){const t=new r(vt.fromRandom().toArray()),e=i.valueAt(t);n.push(new wt(t,e))}const s=this.toPublicKey().toHash("hex").slice(0,8);return new kt(n,t,s)}toBackupShares(t,e){return this.toKeyShares(t,e).toBackupFormat()}static fromBackupShares(t){return vt.fromKeyShares(kt.fromBackupFormat(t))}static fromKeyShares(t){const{points:e,threshold:i,integrity:n}=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 It(e,i),a=new vt(s.valueAt(new r(0)).toArray());if(a.toPublicKey().toHash("hex").slice(0,8)!==n)throw new Error("Integrity hash mismatch");return a}}const _t=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]),Et=[[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))),St=new Uint8Array(256),Pt=new Uint8Array(256);for(let t=0;t<256;t++){const e=255&(t<<1^(128&t?27:0));St[t]=e,Pt[t]=e^t}function Ot(t,e,i){for(let r=0;r<4;r++){const n=e[i+r];for(let e=0;e<4;e++)t[e][r]^=n[e]}}function Nt(t){for(let e=0;e<4;e++)for(let i=0;i<4;i++)t[e][i]=_t[t[e][i]]}function At(t){for(let e=0;e<4;e++)t[e]=_t[t[e]]}function xt(t){const e=t[0];t[0]=t[1],t[1]=t[2],t[2]=t[3],t[3]=e}function Tt(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 Ct(t){for(let e=0;e<4;e++){const i=t[0][e],r=t[1][e],n=t[2][e],s=t[3][e];t[0][e]=St[i]^Pt[r]^n^s,t[1][e]=i^St[r]^Pt[n]^s,t[2][e]=i^r^St[n]^Pt[s],t[3][e]=Pt[i]^r^n^St[s]}}function Rt(t,e){let i,r,n,s;const a=[[],[],[],[]],o=[],c=Array.from(e);if(c.length<=16){for(;c.length<16;)c.unshift(0);s=11}else if(c.length<=24){for(;c.length<24;)c.unshift(0);s=13}else{if(!(e.length<=32))throw new Error("Illegal key length: "+String(e.length));for(;c.length<32;)c.unshift(0);s=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){xt(t),At(t);const r=Et[e/i];for(let e=0;e<4;e++)t[e]^=r[e]}else i>6&&e%i==4&&At(t);for(let n=0;n<4;n++)r[e][n]=r[e-i][n]^t[n]}return r}(s,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(Ot(a,h,0),n=1;n<s;n++)Nt(a),Tt(a),n+1<s&&Ct(a),Ot(a,h,4*n);for(i=0;i<4;i++)for(r=0;r<4;r++)o.push(a[r][i]);return o}const Ft=function(t){return[(4278190080&t)>>>24,(16711680&t)>>16,(65280&t)>>8,255&t]},Bt=function(t){return new Array(t).fill(0)},Lt=[225].concat(Bt(15)),Dt=function(t,e){for(let i=0;i<t.length;i++)t[i]^=e[i]},Mt=function(t){let e,i=0,r=0;for(e=0;e<t.length;e++)r=i,i=1&t[e],t[e]=t[e]>>1,0!==r&&(t[e]=128|t[e]);return t},Vt=function(t,e){const i=e.slice(),r=Bt(16);for(let e=0;e<16;e++)for(let n=7;n>=0;n--)t[e]&1<<n&&Dt(r,i),1&i[15]?(Mt(i),Dt(i,Lt)):Mt(i);return r},qt=function(t){let e;const i=t.slice();for(e=15;11!==e&&(i[e]=i[e]+1,256===i[e]);e--)i[e]=0;return i};function Ht(t,e){let i=Bt(16);for(let r=0;r<t.length;r+=16){const n=i.slice();for(let e=0;e<16;e++)n[e]^=t[r+e]??0;i=Vt(n,e)}return i}function Ut(t,e,i){if(0===t.length)return[];const r=new Array(t.length);let n=e,s=0;const a=Math.ceil(t.length/16);for(let e=0;e<a;e++){const o=Rt(n,i),c=Math.min(16,t.length-s);for(let e=0;e<c;e++)r[s]=t[s]^o[e],s++;e+1<a&&(n=qt(n))}return r}class Kt extends r{static fromRandom(){return new Kt(yt(32))}encrypt(t,e){const i=yt(32);t=W(t,e);const{result:r,authenticationTag:n}=function(t,e,i,r){let n,s;const a=Rt(Bt(16),r);n=[...i],12===i.length?n=n.concat(Bt(3)).concat([1]):(i.length%16!=0&&(n=n.concat(Bt(16-i.length%16))),n=n.concat(Bt(8)),n=Ht(n.concat(Bt(4)).concat(Ft(8*i.length)),a));const o=Ut(t,qt(n),r);return s=e.slice(),0===e.length?s=s.concat(Bt(16)):e.length%16!=0&&(s=s.concat(Bt(16-e.length%16))),s=s.concat(o),0===o.length?s=s.concat(Bt(16)):o.length%16!=0&&(s=s.concat(Bt(16-o.length%16))),s=s.concat(Bt(4)).concat(Ft(8*e.length)).concat(Bt(4)).concat(Ft(8*o.length)),{result:o,authenticationTag:Ut(Ht(s,a),n,r)}}(t,[],i,this.toArray("be",32));return G([...i,...r,...n],e)}decrypt(t,e){const i=(t=W(t,e)).slice(0,32),r=t.slice(32),n=r.slice(-16),s=function(t,e,i,r,n){let s,a;const o=Rt(Bt(16),n);s=[...i],12===i.length?s=s.concat(Bt(3)).concat([1]):(i.length%16!=0&&(s=s.concat(Bt(16-i.length%16))),s=s.concat(Bt(8)),s=Ht(s.concat(Bt(4)).concat(Ft(8*i.length)),o));const c=Ut(t,qt(s),n);return a=e.slice(),0===e.length?a=a.concat(Bt(16)):e.length%16!=0&&(a=a.concat(Bt(16-e.length%16))),a=a.concat(t),0===t.length?a=a.concat(Bt(16)):t.length%16!=0&&(a=a.concat(Bt(16-t.length%16))),a=a.concat(Bt(4)).concat(Ft(8*e.length)).concat(Bt(4)).concat(Ft(8*t.length)),Ut(Ht(a,o),s,n).join()!==r.join()?null:c}(r.slice(0,-16),[],i,n,this.toArray());if(null===s)throw new Error("Decryption failed!");return G(s,e)}}class $t extends dt{static SIGHASH_ALL=1;static SIGHASH_NONE=2;static SIGHASH_SINGLE=3;static SIGHASH_FORKID=64;static SIGHASH_ANYONECANPAY=128;scope;static format(t){const e={sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,sequence:t.inputSequence},i=[...t.otherInputs];function r(e){const i=new it;if(void 0===e)for(const e of t.outputs){const t=e.satoshis??0;i.writeUInt64LE(t);const r=e.lockingScript?.toBinary()??[];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 n=r.satoshis??0;i.writeUInt64LE(n);const s=r.lockingScript?.toBinary()??[];i.writeVarIntNum(s.length),i.write(s)}const r=i.toArray();return H(r)}i.splice(t.inputIndex,0,e);let n=new Array(32).fill(0),s=new Array(32).fill(0),a=new Array(32).fill(0);t.scope&$t.SIGHASH_ANYONECANPAY||(n=(()=>{const t=new it;for(const e of i){if(void 0===e.sourceTXID){if(null==e.sourceTransaction)throw new Error("Missing sourceTransaction for input");t.write(e.sourceTransaction.hash())}else t.writeReverse(W(e.sourceTXID,"hex"));t.writeUInt32LE(e.sourceOutputIndex)}const e=t.toArray();return H(e)})()),t.scope&$t.SIGHASH_ANYONECANPAY||(31&t.scope)===$t.SIGHASH_SINGLE||(31&t.scope)===$t.SIGHASH_NONE||(s=(()=>{const t=new it;for(const e of i){const i=e.sequence??4294967295;t.writeUInt32LE(i)}const e=t.toArray();return H(e)})()),(31&t.scope)!==$t.SIGHASH_SINGLE&&(31&t.scope)!==$t.SIGHASH_NONE?a=r():(31&t.scope)===$t.SIGHASH_SINGLE&&t.inputIndex<t.outputs.length&&(a=r(t.inputIndex));const o=new it;o.writeInt32LE(t.transactionVersion),o.write(n),o.write(s),o.writeReverse(W(t.sourceTXID,"hex")),o.writeUInt32LE(t.sourceOutputIndex);const c=t.subscript.toBinary();o.writeVarIntNum(c.length),o.write(c),o.writeUInt64LE(t.sourceSatoshis);const h=e.sequence;return o.writeUInt32LE(h),o.write(a),o.writeUInt32LE(t.lockTime),o.writeUInt32LE(t.scope>>>0),o.toArray()}static fromChecksigFormat(t){if(0===t.length){const t=new r(1),e=new r(1);return new $t(t,e,1)}const e=t[t.length-1],i=t.slice(0,t.length-1),n=dt.fromDER(i);return new $t(n.r,n.s,e)}constructor(t,e,i){super(t,e),this.scope=i}hasLowS(){return!this.s.ltn(1)&&!this.s.gt(new r("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex"))}toChecksigFormat(){return[...this.toDER(),this.scope]}}class Wt{curve;constructor(){this.curve=new ht}generateProof(t,e,i,r){const n=vt.fromRandom(),s=n.toPublicKey(),a=i.mul(n),o=this.computeChallenge(e,i,r,a,s);return{R:s,SPrime:a,z:n.add(o.mul(t)).umod(this.curve.n)}}verifyProof(t,e,i,r){const{R:n,SPrime:s,z:a}=r,o=this.computeChallenge(t,e,i,s,n),c=this.curve.g.mul(a),h=n.add(t.mul(o));if(!c.eq(h))return!1;const d=e.mul(a),u=s.add(i.mul(o));return!!d.eq(u)}computeChallenge(t,e,i,n,s){const a=[...t.encode(!0),...e.encode(!0),...i.encode(!0),...n.encode(!0),...s.encode(!0)],o=q(a);return new r(o).umod(this.curve.n)}}const zt={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_SUBSTR:127,OP_SPLIT:127,OP_LEFT:128,OP_NUM2BIN:128,OP_RIGHT:129,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_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8: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 zt)zt[zt[t]]=t;const jt=zt;class Xt{chunks;static fromASM(t){const e=[],i=t.split(" ");let r=0;for(;r<i.length;){const t=i[r];let n,s=0;if(t.startsWith("OP_")&&void 0!==jt[t]&&(n=t,s=jt[t]),"0"===t)s=0,e.push({op:s}),r+=1;else if("-1"===t)s=jt.OP_1NEGATE,e.push({op:s}),r+=1;else if(void 0===n){let t=i[r];t.length%2!=0&&(t="0"+t);const n=W(t,"hex");if(G(n,"hex")!==t)throw new Error("invalid hex string in script");const a=n.length;a>=0&&a<jt.OP_PUSHDATA1?s=a:a<Math.pow(2,8)?s=jt.OP_PUSHDATA1:a<Math.pow(2,16)?s=jt.OP_PUSHDATA2:a<Math.pow(2,32)&&(s=jt.OP_PUSHDATA4),e.push({data:n,op:s}),r+=1}else s===jt.OP_PUSHDATA1||s===jt.OP_PUSHDATA2||s===jt.OP_PUSHDATA4?(e.push({data:W(i[r+2],"hex"),op:s}),r+=3):(e.push({op:s}),r+=1)}return new Xt(e)}static fromHex(t){if(0===t.length)return Xt.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.");return Xt.fromBinary(W(t,"hex"))}static fromBinary(t){t=[...t];const e=[];let i=0;const r=new rt(t);for(;!r.eof();){const t=r.readUInt8();if(t===jt.OP_RETURN&&0===i){e.push({op:t,data:r.read()});break}t===jt.OP_IF||t===jt.OP_NOTIF||t===jt.OP_VERIF||t===jt.OP_VERNOTIF?i++:t===jt.OP_ENDIF&&i--;let n=0,s=[];if(t>0&&t<jt.OP_PUSHDATA1)n=t,e.push({data:r.read(n),op:t});else if(t===jt.OP_PUSHDATA1){try{n=r.readUInt8(),s=r.read(n)}catch{r.read()}e.push({data:s,op:t})}else if(t===jt.OP_PUSHDATA2){try{n=r.readUInt16LE(),s=r.read(n)}catch{r.read()}e.push({data:s,op:t})}else if(t===jt.OP_PUSHDATA4){try{n=r.readUInt32LE(),s=r.read(n)}catch{r.read()}e.push({data:s,op:t})}else e.push({op:t})}return new Xt(e)}constructor(t=[]){this.chunks=t}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(){return G(this.toBinary(),"hex")}toBinary(){const t=new it;for(let e=0;e<this.chunks.length;e++){const i=this.chunks[e],r=i.op;if(t.writeUInt8(r),r===jt.OP_RETURN&&null!=i.data){t.write(i.data);break}null!=i.data&&(r<jt.OP_PUSHDATA1?t.write(i.data):r===jt.OP_PUSHDATA1?(t.writeUInt8(i.data.length),t.write(i.data)):r===jt.OP_PUSHDATA2?(t.writeUInt16LE(i.data.length),t.write(i.data)):r===jt.OP_PUSHDATA4&&(t.writeUInt32LE(i.data.length),t.write(i.data)))}return t.toArray()}writeScript(t){return this.chunks=this.chunks.concat(t.chunks),this}writeOpCode(t){return this.chunks.push({op:t}),this}setChunkOpCode(t,e){return this.chunks[t]={op:e},this}writeBn(t){if(t.cmpn(0)===jt.OP_0)this.chunks.push({op:jt.OP_0});else if(0===t.cmpn(-1))this.chunks.push({op:jt.OP_1NEGATE});else if(t.cmpn(1)>=0&&t.cmpn(16)<=0)this.chunks.push({op:t.toNumber()+jt.OP_1-1});else{const e=t.toSm("little");this.writeBin(e)}return this}writeBin(t){let e;if(t.length>0&&t.length<jt.OP_PUSHDATA1)e=t.length;else if(0===t.length)e=jt.OP_0;else if(t.length<Math.pow(2,8))e=jt.OP_PUSHDATA1;else if(t.length<Math.pow(2,16))e=jt.OP_PUSHDATA2;else{if(!(t.length<Math.pow(2,32)))throw new Error("You can't push that much data");e=jt.OP_PUSHDATA4}return this.chunks.push({data:t,op:e}),this}writeNumber(t){return this.writeBn(new r(t)),this}removeCodeseparators(){const t=[];for(let e=0;e<this.chunks.length;e++)this.chunks[e].op!==jt.OP_CODESEPARATOR&&t.push(this.chunks[e]);return this.chunks=t,this}findAndDelete(t){const e=t.toHex();for(let t=0;t<this.chunks.length;t++)e===new Xt([this.chunks[t]]).toHex()&&this.chunks.splice(t,1);return this}isPushOnly(){for(let t=0;t<this.chunks.length;t++)if(this.chunks[t].op>jt.OP_16)return!1;return!0}isLockingScript(){throw new Error("Not implemented")}isUnlockingScript(){throw new Error("Not implemented")}_chunkToString(t){const e=t.op;let i="";return i=void 0===t.data?`${i} ${jt[e]}`:`${i} ${$(t.data)}`,i}}class Gt extends Xt{isLockingScript(){return!0}isUnlockingScript(){return!1}}class Jt extends Xt{isLockingScript(){return!1}isUnlockingScript(){return!0}}const Yt=1073741824,Zt=Math.pow(2,31)-1,Qt=!0,te=Object.freeze(new r(-1).toScriptNum()),ee=Object.freeze(Array.from({length:17},((t,e)=>Object.freeze(new r(e).toScriptNum()))));class ie{sourceTXID;sourceOutputIndex;sourceSatoshis;lockingScript;transactionVersion;otherInputs;outputs;inputIndex;unlockingScript;inputSequence;lockTime;context;programCounter;lastCodeSeparator;stack;altStack;ifStack;memoryLimit;stackMem;altStackMem;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.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0,this.reset()}reset(){this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0}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,n=t[r],s=t[r+1];if(2!==n)return!1;if(0===s)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]||s>1&&0===t[a]&&!(128&t[a+1])||i+s+7!==t.length)}(t))return this.scriptEvaluationError("The signature format is invalid."),!1;try{const e=$t.fromChecksigFormat(t);if(!e.hasLowS())return this.scriptEvaluationError("The signature must have a low S value."),!1;if(!(e.scope&$t.SIGHASH_FORKID))return this.scriptEvaluationError("The signature must use SIGHASH_FORKID."),!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{bt.fromDER(t)}catch(t){return this.scriptEvaluationError("The public key is in an unknown format."),!1}return!0}verifySignature(t,e,i){const n=$t.format({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}),s=new r(H(n));return pt(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>Yt&&this.scriptEvaluationError(`Data push > 1073741824 bytes (pc=${this.programCounter}).`);const n=!this.ifStack.includes(!1);var s,a;if(n&&((s=i)===jt.OP_2MUL||s===jt.OP_2DIV||s===jt.OP_VERIF||s===jt.OP_VERNOTIF||s===jt.OP_VER)&&this.scriptEvaluationError(`This opcode is currently disabled. (Opcode: ${jt[i]}, PC: ${this.programCounter})`),n&&i>=0&&i<=jt.OP_PUSHDATA4)(function(t){const e=t.data,i=t.op;return!(Array.isArray(e)&&(0===e.length?i!==jt.OP_0:1===e.length&&e[0]>=1&&e[0]<=16?i!==jt.OP_1+(e[0]-1):1===e.length&&129===e[0]?i!==jt.OP_1NEGATE:e.length<=75?i!==e.length:e.length<=255?i!==jt.OP_PUSHDATA1:e.length<=65535&&i!==jt.OP_PUSHDATA2))})(e)||this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`),this.pushStack(Array.isArray(e.data)?e.data:[]);else if(n||i>=jt.OP_IF&&i<=jt.OP_ENDIF){let t,e,s,o,c,h,d,u,l,f,p,b,g,m,y,w,I,k,v,_,E,S,P,O,N,A;switch(i){case jt.OP_1NEGATE:this.pushStackCopy(te);break;case jt.OP_0:this.pushStackCopy(ee[0]);break;case jt.OP_1:case jt.OP_2:case jt.OP_3:case jt.OP_4:case jt.OP_5:case jt.OP_6:case jt.OP_7:case jt.OP_8:case jt.OP_9:case jt.OP_10:case jt.OP_11:case jt.OP_12:case jt.OP_13:case jt.OP_14:case jt.OP_15:case jt.OP_16:b=i-(jt.OP_1-1),this.pushStackCopy(ee[b]);break;case jt.OP_NOP:case jt.OP_NOP2:case jt.OP_NOP3:case jt.OP_NOP1:case jt.OP_NOP4:case jt.OP_NOP5:case jt.OP_NOP6:case jt.OP_NOP7:case jt.OP_NOP8:case jt.OP_NOP9:case jt.OP_NOP10:case jt.OP_NOP11:case jt.OP_NOP12:case jt.OP_NOP13:case jt.OP_NOP14:case jt.OP_NOP15:case jt.OP_NOP16:case jt.OP_NOP17:case jt.OP_NOP18:case jt.OP_NOP19:case jt.OP_NOP20:case jt.OP_NOP21:case jt.OP_NOP22:case jt.OP_NOP23:case jt.OP_NOP24:case jt.OP_NOP25:case jt.OP_NOP26:case jt.OP_NOP27:case jt.OP_NOP28:case jt.OP_NOP29:case jt.OP_NOP30:case jt.OP_NOP31:case jt.OP_NOP32:case jt.OP_NOP33:case jt.OP_NOP34:case jt.OP_NOP35:case jt.OP_NOP36:case jt.OP_NOP37:case jt.OP_NOP38:case jt.OP_NOP39:case jt.OP_NOP40:case jt.OP_NOP41:case jt.OP_NOP42:case jt.OP_NOP43:case jt.OP_NOP44:case jt.OP_NOP45:case jt.OP_NOP46:case jt.OP_NOP47:case jt.OP_NOP48:case jt.OP_NOP49:case jt.OP_NOP50:case jt.OP_NOP51:case jt.OP_NOP52:case jt.OP_NOP53:case jt.OP_NOP54:case jt.OP_NOP55:case jt.OP_NOP56:case jt.OP_NOP57:case jt.OP_NOP58:case jt.OP_NOP59:case jt.OP_NOP60:case jt.OP_NOP61:case jt.OP_NOP62:case jt.OP_NOP63:case jt.OP_NOP64:case jt.OP_NOP65:case jt.OP_NOP66:case jt.OP_NOP67:case jt.OP_NOP68:case jt.OP_NOP69:case jt.OP_NOP70:case jt.OP_NOP71:case jt.OP_NOP72:case jt.OP_NOP73:case jt.OP_NOP77:break;case jt.OP_IF:case jt.OP_NOTIF:m=!1,n&&(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(),m=this.castToBool(t),i===jt.OP_NOTIF&&(m=!m)),this.ifStack.push(m);break;case jt.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 jt.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop();break;case jt.OP_VERIFY:this.stack.length<1&&this.scriptEvaluationError("OP_VERIFY requires at least one item to be on the stack."),e=this.stackTop(),m=this.castToBool(e),m||this.scriptEvaluationError("OP_VERIFY requires the top stack value to be truthy."),this.popStack();break;case jt.OP_RETURN:"UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.ifStack=[],this.programCounter--;break;case jt.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 jt.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 jt.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 jt.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),e=this.stackTop(-2),s=this.stackTop(-1),this.pushStackCopy(e),this.pushStackCopy(s);break;case jt.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),e=this.stackTop(-3),s=this.stackTop(-2),o=this.stackTop(-1),this.pushStackCopy(e),this.pushStackCopy(s),this.pushStackCopy(o);break;case jt.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),e=this.stackTop(-4),s=this.stackTop(-3),this.pushStackCopy(e),this.pushStackCopy(s);break;case jt.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(),n=this.popStack(),s=this.popStack();this.pushStack(r),this.pushStack(i),this.pushStack(e),this.pushStack(t),this.pushStack(s),this.pushStack(n);break}case jt.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 jt.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 jt.OP_DEPTH:this.pushStack(new r(this.stack.length).toScriptNum());break;case jt.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),this.popStack();break;case jt.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 jt.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),s=this.popStack(),this.popStack(),this.pushStack(s);break;case jt.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 jt.OP_PICK:case jt.OP_ROLL:{this.stack.length<2&&this.scriptEvaluationError(`${jt[i]} requires at least two items to be on the stack.`),u=r.fromScriptNum(this.popStack(),Qt),b=u.toNumber(),(b<0||b>=this.stack.length)&&this.scriptEvaluationError(`${jt[i]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);const t=this.stack[this.stack.length-1-b];i===jt.OP_ROLL?(this.stack.splice(this.stack.length-1-b,1),this.stackMem-=t.length,this.pushStack(t)):this.pushStackCopy(t);break}case jt.OP_ROT:this.stack.length<3&&this.scriptEvaluationError("OP_ROT requires at least three items to be on the stack."),d=this.popStack(),h=this.popStack(),c=this.popStack(),this.pushStack(h),this.pushStack(d),this.pushStack(c);break;case jt.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 jt.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 jt.OP_SIZE:this.stack.length<1&&this.scriptEvaluationError("OP_SIZE requires at least one item to be on the stack."),this.pushStack(new r(this.stackTop().length).toScriptNum());break;case jt.OP_AND:case jt.OP_OR:case jt.OP_XOR:{this.stack.length<2&&this.scriptEvaluationError(`${jt[i]} requires at least two items on the stack.`),s=this.popStack(),e=this.popStack(),e.length!==s.length&&this.scriptEvaluationError(`${jt[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===jt.OP_AND?t[r]=e[r]&s[r]:i===jt.OP_OR?t[r]=e[r]|s[r]:t[r]=e[r]^s[r];this.pushStack(t);break}case jt.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 jt.OP_LSHIFT:case jt.OP_RSHIFT:{if(this.stack.length<2&&this.scriptEvaluationError(`${jt[i]} requires at least two items to be on the stack.`),f=r.fromScriptNum(this.popStack(),Qt),e=this.popStack(),b=f.toNumber(),b<0&&this.scriptEvaluationError(`${jt[i]} requires the top item on the stack not to be negative.`),0===e.length){this.pushStack([]);break}let t;l=new r(e),t=i===jt.OP_LSHIFT?l.ushln(b):l.ushrn(b);const n=t.toArray("le",e.length);this.pushStack(n);break}case jt.OP_EQUAL:case jt.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${jt[i]} requires at least two items to be on the stack.`),s=this.popStack(),e=this.popStack(),m=function(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}(e,s),this.pushStack(m?[1]:[]),i===jt.OP_EQUALVERIFY&&(m||this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."),this.popStack());break;case jt.OP_1ADD:case jt.OP_1SUB:case jt.OP_NEGATE:case jt.OP_ABS:case jt.OP_NOT:case jt.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${jt[i]} requires at least one item to be on the stack.`),u=r.fromScriptNum(this.popStack(),Qt),i){case jt.OP_1ADD:u=u.add(new r(1));break;case jt.OP_1SUB:u=u.sub(new r(1));break;case jt.OP_NEGATE:u=u.neg();break;case jt.OP_ABS:u.isNeg()&&(u=u.neg());break;case jt.OP_NOT:u=new r(0===u.cmpn(0)?1:0);break;case jt.OP_0NOTEQUAL:u=new r(0!==u.cmpn(0)?1:0)}this.pushStack(u.toScriptNum());break;case jt.OP_ADD:case jt.OP_SUB:case jt.OP_MUL:case jt.OP_DIV:case jt.OP_MOD:case jt.OP_BOOLAND:case jt.OP_BOOLOR:case jt.OP_NUMEQUAL:case jt.OP_NUMEQUALVERIFY:case jt.OP_NUMNOTEQUAL:case jt.OP_LESSTHAN:case jt.OP_GREATERTHAN:case jt.OP_LESSTHANOREQUAL:case jt.OP_GREATERTHANOREQUAL:case jt.OP_MIN:case jt.OP_MAX:{this.stack.length<2&&this.scriptEvaluationError(`${jt[i]} requires at least two items to be on the stack.`),s=this.popStack(),e=this.popStack(),f=r.fromScriptNum(s,Qt),l=r.fromScriptNum(e,Qt);let t=0;switch(i){case jt.OP_MUL:t=l.byteLength()+f.byteLength();break;case jt.OP_ADD:case jt.OP_SUB:t=Math.max(l.byteLength(),f.byteLength())+1;break;default:t=Math.max(l.byteLength(),f.byteLength())}this.ensureStackMem(t);let n=new r(0);switch(i){case jt.OP_ADD:n=l.add(f);break;case jt.OP_SUB:n=l.sub(f);break;case jt.OP_MUL:n=l.mul(f);break;case jt.OP_DIV:0===f.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),n=l.div(f);break;case jt.OP_MOD:0===f.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),n=l.mod(f);break;case jt.OP_BOOLAND:n=new r(0!==l.cmpn(0)&&0!==f.cmpn(0)?1:0);break;case jt.OP_BOOLOR:n=new r(0!==l.cmpn(0)||0!==f.cmpn(0)?1:0);break;case jt.OP_NUMEQUAL:case jt.OP_NUMEQUALVERIFY:n=new r(0===l.cmp(f)?1:0);break;case jt.OP_NUMNOTEQUAL:n=new r(0!==l.cmp(f)?1:0);break;case jt.OP_LESSTHAN:n=new r(l.cmp(f)<0?1:0);break;case jt.OP_GREATERTHAN:n=new r(l.cmp(f)>0?1:0);break;case jt.OP_LESSTHANOREQUAL:n=new r(l.cmp(f)<=0?1:0);break;case jt.OP_GREATERTHANOREQUAL:n=new r(l.cmp(f)>=0?1:0);break;case jt.OP_MIN:n=l.cmp(f)<0?l:f;break;case jt.OP_MAX:n=l.cmp(f)>0?l:f}this.pushStack(n.toScriptNum()),i===jt.OP_NUMEQUALVERIFY&&(this.castToBool(this.stackTop())||this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."),this.popStack());break}case jt.OP_WITHIN:this.stack.length<3&&this.scriptEvaluationError("OP_WITHIN requires at least three items to be on the stack."),p=r.fromScriptNum(this.popStack(),Qt),f=r.fromScriptNum(this.popStack(),Qt),l=r.fromScriptNum(this.popStack(),Qt),m=l.cmp(f)>=0&&l.cmp(p)<0,this.pushStack(m?[1]:[]);break;case jt.OP_RIPEMD160:case jt.OP_SHA1:case jt.OP_SHA256:case jt.OP_HASH160:case jt.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${jt[i]} requires at least one item to be on the stack.`),t=this.popStack();let e=[];i===jt.OP_RIPEMD160?(a=t,e=(new L).update(a,undefined).digest()):i===jt.OP_SHA1?e=(t=>(new M).update(t,void 0).digest())(t):i===jt.OP_SHA256?e=q(t):i===jt.OP_HASH160?e=U(t):i===jt.OP_HASH256&&(e=H(t)),this.pushStack(e);break}case jt.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case jt.OP_CHECKSIG:case jt.OP_CHECKSIGVERIFY:{this.stack.length<2&&this.scriptEvaluationError(`${jt[i]} requires at least two items to be on the stack.`),k=this.popStack(),I=this.popStack(),this.checkSignatureEncoding(I)&&this.checkPublicKeyEncoding(k)||this.scriptEvaluationError(`${jt[i]} requires correct encoding for the public key and signature.`);const t=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);if(w=new Xt(t),w.findAndDelete((new Xt).writeBin(I)),y=!1,I.length>0)try{v=$t.fromChecksigFormat(I),_=bt.fromDER(k),y=this.verifySignature(v,_,w)}catch(t){y=!1}this.pushStack(y?[1]:[]),i===jt.OP_CHECKSIGVERIFY&&(y||this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."),this.popStack());break}case jt.OP_CHECKMULTISIG:case jt.OP_CHECKMULTISIGVERIFY:{E=1,this.stack.length<E&&this.scriptEvaluationError(`${jt[i]} requires at least 1 item for nKeys.`),O=r.fromScriptNum(this.stackTop(-E),Qt).toNumber(),(O<0||O>Zt)&&this.scriptEvaluationError(`${jt[i]} requires a key count between 0 and ${Zt}.`),S=++E,E+=O,this.stack.length<E&&this.scriptEvaluationError(`${jt[i]} stack too small for nKeys and keys. Need ${E}, have ${this.stack.length}.`),N=r.fromScriptNum(this.stackTop(-E),Qt).toNumber(),(N<0||N>O)&&this.scriptEvaluationError(`${jt[i]} requires the number of signatures to be no greater than the number of keys.`),P=++E,E+=N,this.stack.length<E&&this.scriptEvaluationError(`${jt[i]} stack too small for N, keys, M, sigs, and dummy. Need ${E}, have ${this.stack.length}.`);const t=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);w=new Xt(t);for(let t=0;t<N;t++)I=this.stackTop(-P-t),w.findAndDelete((new Xt).writeBin(I));for(y=!0;y&&N>0;){if(0===O){y=!1;break}if(I=this.stackTop(-P),k=this.stackTop(-S),this.checkSignatureEncoding(I)&&this.checkPublicKeyEncoding(k)||this.scriptEvaluationError(`${jt[i]} requires correct encoding for the public key and signature.`),A=!1,I.length>0)try{v=$t.fromChecksigFormat(I),_=bt.fromDER(k),A=this.verifySignature(v,_,w)}catch(t){A=!1}A&&(P++,N--),S++,O--,N>O&&(y=!1)}let e=1+r.fromScriptNum(this.stackTop(-1),!1).toNumber()+1+r.fromScriptNum(this.stackTop(-(1+r.fromScriptNum(this.stackTop(-1),!1).toNumber()+1)),!1).toNumber()+1-1;for(;e>0;)this.popStack(),e--;this.stack.length<1&&this.scriptEvaluationError(`${jt[i]} requires an extra item (dummy) to be on the stack.`),this.popStack().length>0&&this.scriptEvaluationError(`${jt[i]} requires the extra stack item (dummy) to be empty.`),this.pushStack(y?[1]:[]),i===jt.OP_CHECKMULTISIGVERIFY&&(y||this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),this.popStack());break}case jt.OP_CAT:{this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),s=this.popStack(),e=this.popStack();const t=e.concat(s);t.length>Yt&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),this.pushStack(t);break}case jt.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();b=r.fromScriptNum(t,Qt).toNumber(),(b<0||b>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."),this.pushStack(e.slice(0,b)),this.pushStack(e.slice(b));break}case jt.OP_NUM2BIN:{this.stack.length<2&&this.scriptEvaluationError("OP_NUM2BIN requires at least two items to be on the stack."),g=r.fromScriptNum(this.popStack(),Qt).toNumber(),(g>Yt||g<0)&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes or negative size.");let t=this.popStack();if(t=nt(t),t.length>g&&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."),t.length===g){this.pushStack(t);break}const e=new Array(g).fill(0);let i=0;t.length>0&&(i=128&t[t.length-1],t[t.length-1]&=127);for(let i=0;i<t.length;i++)e[i]=t[i];0!==i&&(e[g-1]|=128),this.pushStack(e);break}case jt.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=nt(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}).`)}}return this.programCounter++,!0}validate(){for(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."),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){const e=`Context: ${this.context}, PC: ${this.programCounter}`,i=this.stack.map((t=>null!=t&&void 0!==t.length?$(t):null==t?"null/undef":"INVALID_STACK_ITEM")).join(", "),r=this.altStack.map((t=>null!=t&&void 0!==t.length?$(t):null==t?"null/undef":"INVALID_STACK_ITEM")).join(", "),n=`Stack: [${i}] (len: ${this.stack.length}, mem: ${this.stackMem})`,s=`AltStack: [${r}] (len: ${this.altStack.length}, mem: ${this.altStackMem})`,a=`IfStack: [${this.ifStack.join(", ")}]`;throw new Error(`Script evaluation error: ${t}\nTXID: ${this.sourceTXID}, OutputIdx: ${this.sourceOutputIndex}\n${e}\n${n}\n${s}\n${a}`)}}function re(t){if(null==t)throw new Error("must have value");return t}class ne{lock(t){let e;if("string"==typeof t){const i=et(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 Gt([{op:jt.OP_DUP},{op:jt.OP_HASH160},{op:e.length,data:e},{op:jt.OP_EQUALVERIFY},{op:jt.OP_CHECKSIG}])}unlock(t,e="all",i=!1,r,n){return{sign:async(s,a)=>{let o=$t.SIGHASH_FORKID;"all"===e&&(o|=$t.SIGHASH_ALL),"none"===e&&(o|=$t.SIGHASH_NONE),"single"===e&&(o|=$t.SIGHASH_SINGLE),i&&(o|=$t.SIGHASH_ANYONECANPAY);const c=s.inputs[a],h=s.inputs.filter(((t,e)=>e!==a)),d=c.sourceTXID??c.sourceTransaction?.id("hex");if(null==d||void 0===d)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(""===d)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(n||=c.sourceTransaction?.outputs[c.sourceOutputIndex].lockingScript,null==n)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");const u=$t.format({sourceTXID:d,sourceOutputIndex:re(c.sourceOutputIndex),sourceSatoshis:r,transactionVersion:s.version,otherInputs:h,inputIndex:a,outputs:s.outputs,inputSequence:re(c.sequence),subscript:n,lockTime:s.lockTime,scope:o}),l=t.sign(q(u)),f=new $t(l.r,l.s,o).toChecksigFormat(),p=t.toPublicKey().encode(!0);return new Jt([{op:f.length,data:f},{op:p.length,data:p}])},estimateLength:async()=>108}}}function se(t){if(null==t)throw new Error("must have value");return t}class ae{wallet;originator;static decode(t){const e=bt.fromString($(se(t.chunks[0].data))),i=[];for(let e=2;e<t.chunks.length;e++){const r=t.chunks[e+1]?.op;let n=t.chunks[e].data??[];if(0===n.length&&(t.chunks[e].op>=80&&t.chunks[e].op<=95?n=[t.chunks[e].op-80]:0===t.chunks[e].op?n=[0]:79===t.chunks[e].op&&(n=[129])),i.push(n),r===jt.OP_DROP||r===jt.OP_2DROP)break}return{fields:i,lockingPublicKey:e}}constructor(t,e){this.wallet=t,this.originator=e}async lock(t,e,i,r,n=!1,s=!0,a="before"){const{publicKey:o}=await this.wallet.getPublicKey({protocolID:e,keyID:i,counterparty:r,forSelf:n},this.originator),c=[],h=[];if(c.push({op:o.length/2,data:W(o,"hex")}),c.push({op:jt.OP_CHECKSIG}),s){const n=t.reduce(((t,e)=>[...t,...e]),[]),{signature:s}=await this.wallet.createSignature({data:n,protocolID:e,keyID:i,counterparty:r},this.originator);t.push(s)}for(const e of t)h.push(0===(d=e).length||1===d.length&&0===d[0]?{op:0}:1===d.length&&d[0]>0&&d[0]<=16?{op:80+d[0]}:1===d.length&&129===d[0]?{op:79}:d.length<=75?{op:d.length,data:d}:d.length<=255?{op:76,data:d}:d.length<=65535?{op:77,data:d}:{op:78,data:d});var d;let u=t.length;for(;u>1;)h.push({op:jt.OP_2DROP}),u-=2;return 0!==u&&h.push({op:jt.OP_DROP}),new Gt("before"===a?[...c,...h]:[...h,...c])}unlock(t,e,i,r="all",n=!1,s,a){return{sign:async(o,c)=>{let h=$t.SIGHASH_FORKID;"all"===r&&(h|=$t.SIGHASH_ALL),"none"===r&&(h|=$t.SIGHASH_NONE),"single"===r&&(h|=$t.SIGHASH_SINGLE),n&&(h|=$t.SIGHASH_ANYONECANPAY);const d=o.inputs[c],u=o.inputs.filter(((t,e)=>e!==c)),l=d.sourceTXID??d.sourceTransaction?.id("hex");if(null==l||void 0===l)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(s||=d.sourceTransaction?.outputs[d.sourceOutputIndex].satoshis,null==s||void 0===s)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(a||=d.sourceTransaction?.outputs[d.sourceOutputIndex].lockingScript,null==a)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");const f=$t.format({sourceTXID:l,sourceOutputIndex:se(d.sourceOutputIndex),sourceSatoshis:s,transactionVersion:o.version,otherInputs:u,inputIndex:c,outputs:o.outputs,inputSequence:d.sequence??4294967295,subscript:a,lockTime:o.lockTime,scope:h}),p=q(f),{signature:b}=await this.wallet.createSignature({data:p,protocolID:t,keyID:e,counterparty:i},this.originator),g=dt.fromDER([...b]),m=new $t(g.r,g.s,h).toChecksigFormat();return new Jt([{op:m.length,data:m}])},estimateLength:async()=>73}}}class oe{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 n=t.inputs[r];let s;if(i+=40,"object"==typeof n.unlockingScript)s=n.unlockingScript.toBinary().length;else{if("object"!=typeof n.unlockingScriptTemplate)throw new Error("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");s=await n.unlockingScriptTemplate.estimateLength(t,r)}i+=e(s),i+=s}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 ce{https;constructor(t){this.https=t}async request(t,e){return await new Promise(((i,r)=>{const n=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,n=t.headers["content-type"],s=""!==e&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(e):e;i({status:t.statusCode,statusText:t.statusMessage,ok:r,data:s})}))}));n.on("error",(t=>{r(t)})),null!==e.data&&void 0!==e.data&&n.write(JSON.stringify(e.data)),n.end()}))}}class he{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),n=r.headers.get("Content-Type"),s=n?.startsWith("application/json")?await r.json():await r.text();return{ok:r.ok,status:r.status,statusText:r.statusText,data:s}}}function de(){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 he(window.fetch.bind(window));if("undefined"==typeof require)return t;try{const t=require("https");return new ce(t)}catch(e){return t}}function ue(){return`ts-sdk-${$(yt(16))}`}class le{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(t,e){if(this.URL=t,"string"==typeof e)this.apiKey=e,this.httpClient=de(),this.deploymentId=ue(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const t=e??{},{apiKey:i,deploymentId:r,httpClient:n,callbackToken:s,callbackUrl:a,headers:o}=t;this.apiKey=i,this.httpClient=n??de(),this.deploymentId=r??ue(),this.callbackToken=s,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:n}=t.data,s={status:"success",txid:e,message:`${r} ${i}`};return null!=n&&(s.competingTxs=n),s}{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 fe{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??de(),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 pe{blockHeight;path;static fromHex(t){return pe.fromBinary(W(t,"hex"))}static fromReader(t,e=!0){const i=t.readVarIntNum(),r=t.readUInt8(),n=Array(r).fill(null).map((()=>[]));let s,a,o;for(let e=0;e<r;e++){for(o=t.readVarIntNum();o>0;){a=t.readVarIntNum(),s=t.readUInt8();const i={offset:a};1&s?i.duplicate=!0:(2&s&&(i.txid=!0),i.hash=$(t.read(32).reverse())),Array.isArray(n[e])&&0!==n[e].length||(n[e]=[]),n[e].push(i),o--}n[e].sort(((t,e)=>t.offset-e.offset))}return new pe(i,n,e)}static fromBinary(t){const e=new rt(t);return pe.fromReader(e)}static fromCoinbaseTxidAndHeight(t,e){return new pe(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 n;this.path.forEach(((t,e)=>{if(0===t.length&&0===e)throw new Error(`Empty level at height: ${e}`);const n=new Set;t.forEach((t=>{if(n.has(t.offset))throw new Error(`Duplicate offset: ${t.offset}, at height: ${e}`);if(n.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&&(n=this.computeRoot(t.hash)),n!==this.computeRoot(t.hash))throw new Error("Mismatched roots")}))}toBinary(){const t=new it;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(W(e.hash,"hex").reverse())}}return t.toArray()}toHex(){return $(this.toBinary())}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=>$(H(W(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 n=e>>t^1,s=this.findOrComputeLeaf(t,n);if("object"!=typeof s)throw new Error(`Missing hash for index ${e} at height ${t}`);r=!0===s.duplicate?i((r??"")+(r??"")):i(n%2!=0?(s.hash??"")+(r??""):(r??"")+(s.hash??""))}return r}findOrComputeLeaf(t,e){const i=t=>$(H(W(t,"hex").reverse()).reverse());let r=this.path[t].find((t=>t.offset===e));if(null!=r)return r;if(0===t)return;const n=t-1,s=e<<1,a=this.findOrComputeLeaf(n,s);if(null==a||null==a.hash||""===a.hash)return;const o=this.findOrComputeLeaf(n,s+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 n=e[i].find((e=>e.offset===t.path[i][r].offset));null!=n&&(n.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=[],n=[];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,s=this.path[0][e+(r?-1:1)];void 0!==s.txid&&null!==s.txid&&s.txid||t(s.offset,n)}}e(n,0);for(let t=1;t<this.path.length;t++)n=r,r=i(r),e(n,t)}}class be{_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=$(H(this._rawTx)),this._txid;throw new Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=_e.fromBinary(this._rawTx),this._tx):void 0}get rawTx(){return null!=this._rawTx?this._rawTx:null!=this._tx?(this._rawTx=this._tx.toBinary(),this._rawTx):void 0}constructor(t,e){"string"==typeof t?this._txid=t:Array.isArray(t)?this._rawTx=t:this._tx=t,this.bumpIndex=e,this.updateInputTxids()}static fromTx(t,e){return new be(t,e)}static fromRawTx(t,e){return new be(t,e)}static fromTxid(t,e){return new be(t,e)}updateInputTxids(){if(this.hasProof||null==this.tx)this.inputTxids=[];else{const t={};for(const e of this.tx.inputs)void 0!==e.sourceTXID&&null!==e.sourceTXID&&""!==e.sourceTXID&&(t[e.sourceTXID]=!0);this.inputTxids=Object.keys(t)}}toWriter(t,e){const i=e=>{t.writeUInt8(e)},r=()=>{if(null!=this._rawTx)t.write(this._rawTx);else{if(null==this._tx)throw new Error("a valid serialized Transaction is expected");t.write(this._tx.toBinary())}};e===ye?this.isTxidOnly?(i(Ie.TXID_ONLY),(()=>{if(null==this._txid)throw new Error("Transaction ID (_txid) is undefined");t.writeReverse(W(this._txid,"hex"))})()):void 0!==this.bumpIndex?(i(Ie.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex),r()):(i(Ie.RAWTX),r()):(r(),(()=>{void 0===this.bumpIndex?i(Ie.RAWTX):(i(Ie.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex))})())}static fromReader(t,e){let i,r,n;if(e===ye){const e=t.readUInt8();e===Ie.TXID_ONLY?n=be.fromTxid($(t.readReverse(32))):(e===Ie.RAWTX_AND_BUMP_INDEX&&(r=t.readVarIntNum()),i=_e.fromReader(t),n=be.fromTx(i,r))}else i=_e.fromReader(t),r=0!==t.readUInt8()?t.readVarIntNum():void 0,n=be.fromTx(i,r);return n}}function ge(t){if(null==t)throw new Error("Expected a valid value, but got undefined.");return t}const me=4022206465,ye=4022206466,we=16843009;var Ie,ke;!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"}(Ie||(Ie={}));class ve{bumps=[];txs=[];version=ye;atomicTxid=void 0;constructor(t=ye){this.version=t}findTxid(t){return this.txs.find((e=>e.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.txs.splice(e,1),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(ge(t.sourceTXID));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(ge(r.sourceTXID));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;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 n of i.path[0])if(n.hash===r){t.bumpIndex=e,n.txid=!0;break}}return e}mergeRawTx(t,e){const i=new be(t,e);return this.removeExistingTxid(i.txid),this.txs.push(i),this.tryToValidateBumpIndex(i),i}mergeTransaction(t){const e=t.id("hex");let i;this.removeExistingTxid(e),null!=t.merklePath&&(i=this.mergeBump(t.merklePath));const r=new be(t,i);if(this.txs.push(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.txs.splice(e,1)}mergeTxidOnly(t){let e=this.txs.find((e=>e.txid===t));return null==e&&(e=new be(t),this.txs.push(e),this.tryToValidateBumpIndex(e)),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=Array.isArray(t)?ve.fromBinary(t):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 n=(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,!n(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(){this.sortTxs();const t=new it;return this.toWriter(t),t.toArray()}toBinaryAtomic(t){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 it;return r.writeUInt32LE(we),r.writeReverse(W(t,"hex")),i.toWriter(r),r.toArray()}toHex(){return $(this.toBinary())}static fromReader(t){let e,i=t.readUInt32LE();if(i===we&&(e=$(t.readReverse(32)),i=t.readUInt32LE()),i!==me&&i!==ye)throw new Error(`Serialized BEEF must start with 4022206465 or ${ye} but starts with ${i}`);const r=new ve(i),n=t.readVarIntNum();for(let e=0;e<n;e++){const e=pe.fromReader(t,!1);r.bumps.push(e)}const s=t.readVarIntNum();for(let e=0;e<s;e++){const e=be.fromReader(t,i);r.txs.push(e)}return r.atomicTxid=e,r}static fromBinary(t){const e=new rt(t);return ve.fromReader(e)}static fromString(t,e="hex"){const i=W(t,e),r=new rt(i);return ve.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=[],n=[];for(const s of this.txs)e[s.txid]=s,s.isValid=s.hasProof,s.isValid?(t[s.txid]=!0,r.push(s)):s.isTxidOnly&&0===s.inputTxids.length?(t[s.txid]=!0,n.push(s)):i.push(s);const s={},a=[],o=i;i=[];for(const t of o){let r=!1;for(const i of t.inputTxids)void 0===e[i]&&(s[i]=!0,r=!0);r?a.push(t):i.push(t)}for(;i.length>0;){const e=i;i=[];for(const n of e)n.inputTxids.every((e=>t[e]))?(t[n.txid]=!0,r.push(n)):i.push(n);if(e.length===i.length)break}const c=i;return this.txs=a.concat(c).concat(n).concat(r),{missingInputs:Object.keys(s),notValid:c.map((t=>t.txid)),valid:Object.keys(t),withMissingInputs:a.map((t=>t.txid)),txidOnly:n.map((t=>t.txid))}}clone(){const t=new ve;return t.version=this.version,t.bumps=Array.from(this.bumps),t.txs=Array.from(this.txs),t}trimKnownTxids(t){for(let e=0;e<this.txs.length;){const i=this.txs[e];i.isTxidOnly&&t.includes(i.txid)?this.txs.splice(e,1):e++}}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(){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 n=e.path[i-1].find((t=>t.offset===r.offset+1)),s=r.offset>>1;void 0!==n&&"string"==typeof n.hash&&e.path[i].every((t=>t.offset!==s))&&e.path[i].push({offset:s,hash:(t=n.hash+r.hash,$(H(W(t,"hex").reverse()).reverse()))})}var t}}class _e{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;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}=_e.fromAnyBeef(t,e);return i}static fromAtomicBEEF(t){const{tx:e,txid:i,beef:r}=_e.fromAnyBeef(t);if(i!==r.atomicTxid)throw 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=ve.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,n=i.findAtomicTransaction(r);if(null==n)throw e?new Error(`Transaction with TXID ${r} not found in BEEF data.`):new Error("beef does not contain transaction for atomic txid.");return{tx:n,beef:i,txid:r}}static fromEF(t){const e=new rt(t),i=e.readUInt32LE();if("0000000000ef"!==$(e.read(6)))throw new Error("Invalid EF marker");const r=e.readVarIntNum(),n=[];for(let t=0;t<r;t++){const t=$(e.readReverse(32)),i=e.readUInt32LE(),r=e.readVarIntNum(),s=e.read(r),a=Jt.fromBinary(s),o=e.readUInt32LE(),c=e.readUInt64LEBn().toNumber(),h=e.readVarIntNum(),d=e.read(h),u=Gt.fromBinary(d),l=new _e(void 0,[],[],void 0);l.outputs=Array(i+1).fill(null),l.outputs[i]={satoshis:c,lockingScript:u},n.push({sourceTransaction:l,sourceTXID:t,sourceOutputIndex:i,unlockingScript:a,sequence:o})}const s=e.readVarIntNum(),a=[];for(let t=0;t<s;t++){const t=e.readUInt64LEBn().toNumber(),i=e.readVarIntNum(),r=e.read(i),n=Gt.fromBinary(r);a.push({satoshis:t,lockingScript:n})}const o=e.readUInt32LE();return new _e(i,n,a,o)}static parseScriptOffsets(t){const e=new rt(t),i=[],r=[];e.pos+=4;const n=e.readVarIntNum();for(let t=0;t<n;t++){e.pos+=36;const r=e.readVarIntNum();i.push({vin:t,offset:e.pos,length:r}),e.pos+=r+4}const s=e.readVarIntNum();for(let t=0;t<s;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=$(t.readReverse(32)),i=t.readUInt32LE(),n=t.readVarIntNum(),s=t.read(n),a=Jt.fromBinary(s),o=t.readUInt32LE();r.push({sourceTXID:e,sourceOutputIndex:i,unlockingScript:a,sequence:o})}const n=t.readVarIntNum(),s=[];for(let e=0;e<n;e++){const e=t.readUInt64LEBn().toNumber(),i=t.readVarIntNum(),r=t.read(i),n=Gt.fromBinary(r);s.push({satoshis:e,lockingScript:n})}const a=t.readUInt32LE();return new _e(e,r,s,a)}static fromBinary(t){const e=new rt(t);return _e.fromReader(e)}static fromHex(t){return _e.fromBinary(W(t,"hex"))}static fromHexEF(t){return _e.fromEF(W(t,"hex"))}static fromHexBEEF(t,e){return _e.fromBEEF(W(t,"hex"),e)}constructor(t=1,e=[],i=[],r=0,n=new Map,s){this.version=t,this.inputs=e,this.outputs=i,this.lockTime=r,this.metadata=n,this.merklePath=s}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.cachedHash=void 0,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 ne).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=new oe(1),e="equal"){if(this.cachedHash=void 0,"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 n=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);n[t]=n[t]+e,i+=e,r-=e}for(const t of this.outputs)!0===t.change&&(t.satoshis=n.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.cachedHash=void 0;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 le(t?"https://arc-test.taal.com":"https://arc.taal.com",e)}()){return await t.broadcast(this)}toBinary(){const t=new it;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(W(e.sourceTXID,"hex"));if(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??0)}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)}return t.writeUInt32LE(this.lockTime),t.toArray()}toEF(){const t=new it;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(W(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??0),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)}return t.writeUInt32LE(this.lockTime),t.toArray()}toHexEF(){return $(this.toEF())}toHex(){return $(this.toBinary())}toHexBEEF(){return $(this.toBEEF())}toHexAtomicBEEF(){return $(this.toAtomicBEEF())}hash(t){let e;return null!=this.cachedHash?e=this.cachedHash:(e=H(this.toBinary()),this.cachedHash=e),"hex"===t?$(e):e}id(t){const e=[...this.hash()];return e.reverse(),"hex"===t?$(e):e}async verify(t=function(){return new fe}(),e,i){const r=new Set,n=[this];for(;n.length>0;){const s=n.shift(),a=s?.id("hex")??"";if(null!=a&&""!==a&&r.has(a))continue;if("object"==typeof s?.merklePath){if("scripts only"===t){null!=a&&r.add(a);continue}if(await s.merklePath.verify(a,t)){r.add(a);continue}}if(void 0!==e){if(void 0===s)throw new Error("Transaction is undefined");const t=_e.fromEF(s.toEF());if(delete t.outputs[0].satoshis,t.outputs[0].change=!0,await t.fee(e),s.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===s)throw new Error("Transaction is undefined");for(let t=0;t<s.inputs.length;t++){const e=s.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)||n.push(e.sourceTransaction);const d=s.inputs.filter(((e,i)=>i!==t));if(void 0===e.sourceTXID&&(e.sourceTXID=h),!new ie({sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:s.version,otherInputs:d,unlockingScript:e.unlockingScript,inputSequence:e.sequence??0,inputIndex:t,outputs:s.outputs,lockTime:s.lockTime,memoryLimit:i}).validate())return!1}let c=0;for(const t of s.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}toBEEF(t){const e=new it;e.writeUInt32LE(me);const i=[],r=[],n=e=>{const s={tx:e},a="object"==typeof e.merklePath;if(a){let t=!1;for(let r=0;r<i.length;r++){if(i[r]===e.merklePath){s.pathIndex=r,t=!0;break}if(null!==e.merklePath&&void 0!==e.merklePath&&i[r].blockHeight===e.merklePath.blockHeight&&i[r].computeRoot()===e.merklePath.computeRoot()){i[r].combine(e.merklePath),s.pathIndex=r,t=!0;break}}t||(s.pathIndex=i.length,null!==e.merklePath&&void 0!==e.merklePath&&i.push(e.merklePath))}if(r.some((t=>t.tx.id("hex")===e.id("hex")))||r.unshift(s),!a)for(let i=0;i<e.inputs.length;i++){const r=e.inputs[i];if("object"==typeof r.sourceTransaction)n(r.sourceTransaction);else if(!1===t)throw new Error("A required source transaction is missing!")}};n(this),e.writeVarIntNum(i.length);for(const t of i)e.write(t.toBinary());e.writeVarIntNum(r.length);for(const t of r)e.write(t.tx.toBinary()),"number"==typeof t.pathIndex?(e.writeUInt8(1),e.writeVarIntNum(t.pathIndex)):e.writeUInt8(0);return e.toArray()}toAtomicBEEF(t){const e=new it;e.writeUInt32LE(16843009),e.write(this.hash());const i=this.toBEEF(t);return e.write(i),e.toArray()}}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"}(ke||(ke={}));class Ee{rootKey;identityKey;constructor(t){this.rootKey="anyone"===t?new vt(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)).toPublicKey():i.deriveChild(this.rootKey,this.computeInvoiceNumber(t,e))}derivePrivateKey(t,e,i){return i=this.normalizeCounterparty(i),this.rootKey.deriveChild(i,this.computeInvoiceNumber(t,e))}deriveSymmetricKey(t,e,i){"anyone"===i&&(i=new vt(1).toPublicKey()),i=this.normalizeCounterparty(i);const r=this.derivePublicKey(t,e,i),n=this.derivePrivateKey(t,e,i);return new Kt(n.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),n=W(this.computeInvoiceNumber(e,i),"utf8");return K(r.encode(!0),n)}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 vt(1).toPublicKey():"string"==typeof t?bt.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}`}}const Se=class{keyDeriver;constructor(t){"string"!=typeof t.identityKey&&(t=new Ee(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 Wt).generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),bt.fromString(t.counterparty),ot.fromDER(i)),n=[...r.R.encode(!0),...r.SPrime.encode(!0),...r.z.toArray()],s=(new Date).toISOString(),{ciphertext:a}=await this.encrypt({plaintext:i,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:t.verifier}),{ciphertext:o}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:t.verifier});return{prover:e,verifier:t.verifier,counterparty:t.counterparty,revelationTime:s,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:n}=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:n,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){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:K(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=K(e.toArray(),t.data).toString()===t.hmac.toString();if(!i){const t=new Error("HMAC is not valid");throw t.code="ERR_INVALID_HMAC",t}return{valid:i}}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??q(t.data??[]),i=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePrivateKey(t.protocolID,t.keyID,t.counterparty??"anyone");return{signature:ft(new r(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??q(t.data??[]),i=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePublicKey(t.protocolID,t.keyID,t.counterparty??"self",t.forSelf),n=pt(new r(e),dt.fromDER(t.signature),i);if(!n){const t=new Error("Signature is not valid");throw t.code="ERR_INVALID_SIGNATURE",t}return{valid:n}}};class Pe{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 Oe 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)}}var Ne,Ae,xe;!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"}(Ne||(Ne={}));class Te{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 n=J(yt(12)),s=t=>{if("CWI"===t.data.type&&t.isTrusted&&t.data.id===n&&!0!==t.data.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",s),"error"===t.data.status){const e=new Oe(t.data.description,t.data.code);r(e)}else i(t.data.result)};window.addEventListener("message",s),window.parent.postMessage({type:"CWI",isInvocation:!0,id:n,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 Ce{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(t,e,i,r,n,s,a){this.type=t,this.serialNumber=e,this.subject=i,this.certifier=r,this.revocationOutpoint=n,this.fields=s,this.signature=a}toBinary(t=!0){const e=new it,i=W(this.type,"base64");e.write(i);const r=W(this.serialNumber,"base64");e.write(r);const n=W(this.subject,"hex");e.write(n);const s=W(this.certifier,"hex");e.write(s);const[a,o]=this.revocationOutpoint.split("."),c=W(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=W(t,"utf8");e.writeVarIntNum(r.length),e.write(r);const n=W(i,"utf8");e.writeVarIntNum(n.length),e.write(n)}if(t&&(this.signature??"").length>0){const t=W(this.signature,"hex");e.write(t)}return e.toArray()}static fromBinary(t){const e=new rt(t),i=J(e.read(32)),r=J(e.read(32)),n=e.read(33),s=$(n),a=e.read(33),o=$(a),c=e.read(32),h=`${$(c)}.${e.readVarIntNum()}`,d=e.readVarIntNum(),u={};for(let t=0;t<d;t++){const t=e.readVarIntNum(),i=e.read(t),r=X(i),n=e.readVarIntNum(),s=e.read(n),a=X(s);u[r]=a}let l;if(!e.eof()){const t=e.read();l=dt.fromDER(t).toString("hex")}return new Ce(i,r,s,o,h,u,l)}async verify(){const t=new Se("anyone"),e=this.toBinary(!1),i=this.signature??"",{valid:r}=await t.verifySignature({signature:W(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=$(i)}static getCertificateFieldEncryptionDetails(t,e){return{protocolID:[2,"certificate field encryption"],keyID:e?`${e} ${t}`:t}}}(xe=Ae||(Ae={}))[xe.createAction=1]="createAction",xe[xe.signAction=2]="signAction",xe[xe.abortAction=3]="abortAction",xe[xe.listActions=4]="listActions",xe[xe.internalizeAction=5]="internalizeAction",xe[xe.listOutputs=6]="listOutputs",xe[xe.relinquishOutput=7]="relinquishOutput",xe[xe.getPublicKey=8]="getPublicKey",xe[xe.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",xe[xe.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",xe[xe.encrypt=11]="encrypt",xe[xe.decrypt=12]="decrypt",xe[xe.createHmac=13]="createHmac",xe[xe.verifyHmac=14]="verifyHmac",xe[xe.createSignature=15]="createSignature",xe[xe.verifySignature=16]="verifySignature",xe[xe.acquireCertificate=17]="acquireCertificate",xe[xe.listCertificates=18]="listCertificates",xe[xe.proveCertificate=19]="proveCertificate",xe[xe.relinquishCertificate=20]="relinquishCertificate",xe[xe.discoverByIdentityKey=21]="discoverByIdentityKey",xe[xe.discoverByAttributes=22]="discoverByAttributes",xe[xe.isAuthenticated=23]="isAuthenticated",xe[xe.waitForAuthentication=24]="waitForAuthentication",xe[xe.getHeight=25]="getHeight",xe[xe.getHeaderForHeight=26]="getHeaderForHeight",xe[xe.getNetwork=27]="getNetwork",xe[xe.getVersion=28]="getVersion";const Re=Ae;class Fe{wire;constructor(t){this.wire=t}async transmit(t,e="",i=[]){const r=new it;r.writeUInt8(Re[t]);const n=W(e,"utf8");r.writeUInt8(n.length),r.write(n),i.length>0&&r.write(i);const s=r.toArray(),a=await this.wire.transmitToWallet(s),o=new rt(a),c=o.readUInt8();if(0===c)return o.read();{const t=o.readVarIntNum(),e=o.read(t),i=X(e),r=o.readVarIntNum(),n=o.read(r),s=X(n);throw new Oe(i,c,s)}}async createAction(t,e){const i=new it,r=W(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=W(e.unlockingScript,"hex");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1),i.writeVarIntNum(e.unlockingScriptLength??0);const t=W(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=W(e.lockingScript,"hex");i.writeVarIntNum(t.length),i.write(t),i.writeVarIntNum(e.satoshis);const r=W(e.outputDescription,"utf8");if(i.writeVarIntNum(r.length),i.write(r),null!=e.basket&&""!==e.basket){const t=W(e.basket,"utf8");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1);if(null!=e.customInstructions&&""!==e.customInstructions){const t=W(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=W(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=W(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=W(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=W(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 n=await this.transmit("createAction",e,i.toArray()),s=new rt(n),a={};if(1===s.readInt8()){const t=s.read(32);a.txid=$(t)}if(1===s.readInt8()){const t=s.readVarIntNum();a.tx=s.read(t)}const o=s.readVarIntNum();if(o>=0){a.noSendChange=[];for(let t=0;t<o;t++){const t=this.readOutpoint(s);a.noSendChange.push(t)}}const c=s.readVarIntNum();if(c>=0){a.sendWithResults=[];for(let t=0;t<c;t++){const t=s.read(32),e=$(t),i=s.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===s.readInt8()){const t=s.readVarIntNum(),e=s.read(t),i=s.readVarIntNum(),r=s.read(i);a.signableTransaction={tx:e,reference:J(r)}}return a}async signAction(t,e){const i=new it,r=Object.keys(t.spends);i.writeVarIntNum(r.length);for(const e of r){i.writeVarIntNum(Number(e));const r=t.spends[Number(e)],n=W(r.unlockingScript,"hex");i.writeVarIntNum(n.length),i.write(n),"number"==typeof r.sequenceNumber?i.writeVarIntNum(r.sequenceNumber):i.writeVarIntNum(-1)}const n=W(t.reference,"base64");if(i.writeVarIntNum(n.length),i.write(n),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=W(e,"hex");i.write(t)}}else i.writeVarIntNum(-1);else i.writeInt8(0);const s=await this.transmit("signAction",e,i.toArray()),a=new rt(s),o={};if(1===a.readInt8()){const t=a.read(32);o.txid=$(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=$(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,W(t.reference,"base64")),{aborted:!0}}async listActions(t,e){const i=new it;i.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=W(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 n=await this.transmit("listActions",e,i.toArray()),s=new rt(n),a=s.readVarIntNum(),o=[];for(let t=0;t<a;t++){const t=s.read(32),e=$(t),i=s.readVarIntNum(),r=s.readInt8();let n;switch(r){case 1:n="completed";break;case 2:n="unprocessed";break;case 3:n="sending";break;case 4:n="unproven";break;case 5:n="unsigned";break;case 6:n="nosend";break;case 7:n="nonfinal";break;case 8:n="failed";break;default:throw new Error(`Unknown status code: ${r}`)}const a=1===s.readInt8(),c=s.readVarIntNum(),h=s.read(c),d={txid:e,satoshis:i,status:n,isOutgoing:a,description:X(h),version:0,lockTime:0},u=s.readVarIntNum();if(u>=0){d.labels=[];for(let t=0;t<u;t++){const t=s.readVarIntNum(),e=s.read(t);d.labels.push(X(e))}}d.version=s.readVarIntNum(),d.lockTime=s.readVarIntNum();const l=s.readVarIntNum();if(l>=0){d.inputs=[];for(let t=0;t<l;t++){const t=this.readOutpoint(s),e=s.readVarIntNum(),i=s.readVarIntNum();let r;if(i>=0){const t=s.read(i);r=$(t)}const n=s.readVarIntNum();let a;if(n>=0){const t=s.read(n);a=$(t)}const o=s.readVarIntNum(),c=s.read(o),h=X(c),u=s.readVarIntNum();d.inputs.push({sourceOutpoint:t,sourceSatoshis:e,sourceLockingScript:r,unlockingScript:a,inputDescription:h,sequenceNumber:u})}}const f=s.readVarIntNum();if(f>=0){d.outputs=[];for(let t=0;t<f;t++){const t=s.readVarIntNum(),e=s.readVarIntNum(),i=s.readVarIntNum();let r;if(i>=0){const t=s.read(i);r=$(t)}const n=1===s.readInt8(),a=s.readVarIntNum(),o=s.read(a),c=X(o),h=s.readVarIntNum();let u;if(h>=0){const t=s.read(h);u=X(t)}const l=s.readVarIntNum(),f=[];if(l>=0)for(let t=0;t<l;t++){const t=s.readVarIntNum(),e=s.read(t);f.push(X(e))}const p=s.readVarIntNum();let b;if(p>=0){const t=s.read(p);b=X(t)}d.outputs.push({outputIndex:t,satoshis:e,lockingScript:r,spendable:n,outputDescription:c,basket:u,tags:f,customInstructions:b})}}o.push(d)}return{totalActions:a,actions:o}}async internalizeAction(t,e){const i=new it;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(W(e.paymentRemittance.senderIdentityKey,"hex"));const t=W(e.paymentRemittance.derivationPrefix,"base64");i.writeVarIntNum(t.length),i.write(t);const r=W(e.paymentRemittance.derivationSuffix,"base64");i.writeVarIntNum(r.length),i.write(r)}else{i.writeUInt8(2);const t=W(e.insertionRemittance?.basket,"utf8");if(i.writeVarIntNum(t.length),i.write(t),"string"==typeof e.insertionRemittance?.customInstructions&&""!==e.insertionRemittance.customInstructions){const t=W(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=W(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=W(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}}else i.writeVarIntNum(-1);const r=W(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 it,r=W(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=W(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 n=await this.transmit("listOutputs",e,i.toArray()),s=new rt(n),a=s.readVarIntNum(),o=s.readVarIntNum();let c;o>=0&&(c=s.read(o));const h=[];for(let t=0;t<a;t++){const t={spendable:!0,outpoint:this.readOutpoint(s),satoshis:s.readVarIntNum()},e=s.readVarIntNum();e>=0&&(t.lockingScript=$(s.read(e)));const i=s.readVarIntNum();i>=0&&(t.customInstructions=X(s.read(i)));const r=s.readVarIntNum();if(-1!==r){const e=[];for(let t=0;t<r;t++){const t=s.readVarIntNum();e.push(X(s.read(t)))}t.tags=e}const n=s.readVarIntNum();if(-1!==n){const e=[];for(let t=0;t<n;t++){const t=s.readVarIntNum();e.push(X(s.read(t)))}t.labels=e}h.push(t)}return{totalOutputs:a,BEEF:c,outputs:h}}async relinquishOutput(t,e){const i=new it,r=W(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 it,[i,r]=t.split(".");return e.write(W(i,"hex")),e.writeVarIntNum(Number(r)),e.toArray()}readOutpoint(t){return`${$(t.read(32))}.${t.readVarIntNum()}`}async getPublicKey(t,e){const i=new it;i.writeUInt8(t.identityKey?1:0),t.identityKey?i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)):(i.write(this.encodeKeyRelatedParams(t.protocolID??=[ke.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:$(r)}}async revealCounterpartyKeyLinkage(t,e){const i=new it;i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),i.write(W(t.counterparty,"hex")),i.write(W(t.verifier,"hex"));const r=await this.transmit("revealCounterpartyKeyLinkage",e,i.toArray()),n=new rt(r),s=$(n.read(33)),a=$(n.read(33)),o=$(n.read(33)),c=n.readVarIntNum(),h=X(n.read(c)),d=n.readVarIntNum(),u=n.read(d),l=n.readVarIntNum();return{prover:s,verifier:a,counterparty:o,revelationTime:h,encryptedLinkage:u,encryptedLinkageProof:n.read(l)}}async revealSpecificKeyLinkage(t,e){const i=new it;i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.write(W(t.verifier,"hex"));const r=await this.transmit("revealSpecificKeyLinkage",e,i.toArray()),n=new rt(r),s=$(n.read(33)),a=$(n.read(33)),o=$(n.read(33)),c=n.readUInt8(),h=n.readVarIntNum(),d=X(n.read(h)),u=n.readVarIntNum(),l=X(n.read(u)),f=n.readVarIntNum(),p=n.read(f),b=n.readVarIntNum();return{prover:s,verifier:a,counterparty:o,protocolID:[c,d],keyID:l,encryptedLinkage:p,encryptedLinkageProof:n.read(b),proofType:n.readUInt8()}}async encrypt(t,e){const i=new it;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 it;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 it;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 it;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 it;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 it;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,n){const s=new it;s.writeUInt8(t[0]);const a=W(t[1],"utf8");s.writeVarIntNum(a.length),s.write(a);const o=W(e,"utf8");return s.writeVarIntNum(o.length),s.write(o),"string"!=typeof i?s.writeUInt8(0):"self"===i?s.writeUInt8(11):"anyone"===i?s.writeUInt8(12):s.write(W(i,"hex")),s.write(this.encodePrivilegedParams(r,n)),s.toArray()}async acquireCertificate(t,e){const i=new it;i.write(W(t.type,"base64")),i.write(W(t.certifier,"hex"));const r=Object.entries(t.fields);i.writeVarIntNum(r.length);for(const[t,e]of r){const r=W(t,"utf8"),n=W(e,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(n.length),i.write(n)}if(i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),i.writeUInt8("direct"===t.acquisitionProtocol?1:2),"direct"===t.acquisitionProtocol){i.write(W(t.serialNumber,"base64")),i.write(this.encodeOutpoint(t.revocationOutpoint??""));const e=W(t.signature,"hex");i.writeVarIntNum(e.length),i.write(e);const r="certifier"!==t.keyringRevealer?W(t.keyringRevealer,"hex"):[11];i.write(r);const n=Object.keys(t.keyringForSubject??{});i.writeVarIntNum(n.length);for(let e=0;e<n.length;e++){const r=W(n[e],"utf8");i.writeVarIntNum(r.length),i.write(r);const s=W(t.keyringForSubject?.[n[e]],"base64");i.writeVarIntNum(s.length),i.write(s)}}else{const e=W(t.certifierUrl,"utf8");i.writeVarIntNum(e.length),i.write(e)}const n=await this.transmit("acquireCertificate",e,i.toArray()),s=Ce.fromBinary(n);return{...s,signature:s.signature}}encodePrivilegedParams(t,e){const i=new it;if("boolean"==typeof t?i.writeInt8(t?1:0):i.writeInt8(-1),"string"==typeof e){const t=W(e,"utf8");i.writeInt8(t.length),i.write(t)}else i.writeInt8(-1);return i.toArray()}async listCertificates(t,e){const i=new it;i.writeVarIntNum(t.certifiers.length);for(let e=0;e<t.certifiers.length;e++)i.write(W(t.certifiers[e],"hex"));i.writeVarIntNum(t.types.length);for(let e=0;e<t.types.length;e++)i.write(W(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()),n=new rt(r),s=n.readVarIntNum(),a=[];for(let t=0;t<s;t++){const t=n.readVarIntNum(),e=n.read(t),i=Ce.fromBinary(e);a.push({...i,signature:i.signature})}return{totalCertificates:s,certificates:a}}async proveCertificate(t,e){const i=new it,r=W(t.certificate.type,"base64");i.write(r);const n=W(t.certificate.subject,"hex");i.write(n);const s=W(t.certificate.serialNumber,"base64");i.write(s);const a=W(t.certificate.certifier,"hex");i.write(a);const o=this.encodeOutpoint(t.certificate.revocationOutpoint??"");i.write(o);const c=W(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=W(t,"utf8"),n=W(e,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(n.length),i.write(n)}i.writeVarIntNum(t.fieldsToReveal.length);for(const e of t.fieldsToReveal){const t=W(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}i.write(W(t.verifier,"hex")),i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason));const d=await this.transmit("proveCertificate",e,i.toArray()),u=new rt(d),l=u.readVarIntNum(),f={};for(let t=0;t<l;t++){const t=u.readVarIntNum(),e=X(u.read(t)),i=u.readVarIntNum();f[e]=J(u.read(i))}return{keyringForVerifier:f}}async relinquishCertificate(t,e){const i=new it,r=W(t.type,"base64");i.write(r);const n=W(t.serialNumber,"base64");i.write(n);const s=W(t.certifier,"hex");return i.write(s),await this.transmit("relinquishCertificate",e,i.toArray()),{relinquished:!0}}parseDiscoveryResult(t){const e=new rt(t),i=e.readVarIntNum(),r=[];for(let t=0;t<i;t++){const t=e.readVarIntNum(),i=e.read(t),n=Ce.fromBinary(i),s=e.readVarIntNum(),a=X(e.read(s)),o=e.readVarIntNum(),c=X(e.read(o)),h=e.readVarIntNum(),d=X(e.read(h)),u=e.readUInt8(),l={},f=e.readVarIntNum();for(let t=0;t<f;t++){const t=e.readVarIntNum(),i=X(e.read(t)),r=e.readVarIntNum();l[i]=e.read(r)}const p={},b=e.readVarIntNum();for(let t=0;t<b;t++){const t=e.readVarIntNum(),i=X(e.read(t)),r=e.readVarIntNum();p[i]=X(e.read(r))}r.push({...n,signature:n.signature,certifierInfo:{iconUrl:c,name:a,description:d,trust:u},publiclyRevealedKeyring:l,decryptedFields:p})}return{totalCertificates:i,certificates:r}}async discoverByIdentityKey(t,e){const i=new it;i.write(W(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 it,r=Object.keys(t.attributes);i.writeVarIntNum(r.length);for(let e=0;e<r.length;e++)i.writeVarIntNum(r[e].length),i.write(W(r[e],"utf8")),i.writeVarIntNum(t.attributes[r[e]].length),i.write(W(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 n=await this.transmit("discoverByAttributes",e,i.toArray());return this.parseDiscoveryResult(n)}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 rt(i).readVarIntNum()}}async getHeaderForHeight(t,e){const i=new it;i.writeVarIntNum(t.height);const r=await this.transmit("getHeaderForHeight",e,i.toArray());return{header:$(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:X(i)}}}class Be{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 rt(t),i=e.readUInt8(),r=Re[i];if(void 0===r||""===r)throw new Error(`Invalid call code: ${i}`);const n=e.readUInt8();let s;if(n>0){const t=e.read(n);s=X(t)}const a=e.read(),o=await fetch(`${this.baseUrl}/${r}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:s??""},body:new Uint8Array(a)}),c=await o.arrayBuffer();return Array.from(new Uint8Array(c))}}class Le extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(t,e,i,r,n){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=t,this.sendWithResults=e,this.txid=i,this.tx=r,this.noSendChange=n,this.code=5,this.name=this.constructor.name}}class De{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;this.api=async(t,e)=>{const n=!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,s=await await i(`${this.baseUrl}/${t}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...n?{Origin:n}:{}},body:JSON.stringify(e)}),a=await s.json();if(!s.ok){if(400===s.status&&a.isError&&5===a.code)throw new Le(a.reviewActionResults,a.sendWithResults,a.txid,a.tx,a.noSendChange);{const i={call:t,args:e,message:a.message??`HTTP Client error ${s.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 Me{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 n=J(yt(12)),s=t=>{const e=JSON.parse(t.data);if("CWI"===e.type&&e.id===n&&!0!==e.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",s),"error"===e.status){const t=new Oe(e.description,e.code);r(t)}else i(e.result)};window.addEventListener("message",s),window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:n,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)}}class Ve{substrate;originator;constructor(t="auto",e){"Cicada"===t&&(t=new Fe(new Be(e))),"window.CWI"===t&&(t=new Pe),"XDM"===t&&(t=new Te),"json-api"===t&&(t=new De(e)),"react-native"===t&&(t=new Me(e)),this.substrate=t,this.originator=e}async connectToSubstrate(){if("object"==typeof this.substrate)return;let t;const e=async e=>{let i;if(i="number"==typeof e?await Promise.race([t.getVersion({}),new Promise(((t,i)=>setTimeout((()=>i(new Error("Timed out."))),e)))]):await t.getVersion({}),"object"!=typeof i||"string"!=typeof i.version)throw new Error("Failed to use substrate.")};try{t=new Pe,await e(),this.substrate=t}catch(i){try{t=new Te,await e(200),this.substrate=t}catch(i){try{t=new Fe(new Be(this.originator)),await e(),this.substrate=t}catch(i){try{t=new De(this.originator),await e(),this.substrate=t}catch(i){try{t=new Me(this.originator),await e(),this.substrate=t}catch(t){throw new Error("No wallet available over any communication substrate. Install a BSV wallet today!")}}}}}}async createAction(t){return await this.connectToSubstrate(),await this.substrate.createAction(t,this.originator)}async signAction(t){return await this.connectToSubstrate(),await this.substrate.signAction(t,this.originator)}async abortAction(t){return await this.connectToSubstrate(),await this.substrate.abortAction(t,this.originator)}async listActions(t){return await this.connectToSubstrate(),await this.substrate.listActions(t,this.originator)}async internalizeAction(t){return await this.connectToSubstrate(),await this.substrate.internalizeAction(t,this.originator)}async listOutputs(t){return await this.connectToSubstrate(),await this.substrate.listOutputs(t,this.originator)}async relinquishOutput(t){return 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.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){return await this.connectToSubstrate(),await this.substrate.acquireCertificate(t,this.originator)}async listCertificates(t){return await this.connectToSubstrate(),await this.substrate.listCertificates(t,this.originator)}async proveCertificate(t){return await this.connectToSubstrate(),await this.substrate.proveCertificate(t,this.originator)}async relinquishCertificate(t){return await this.connectToSubstrate(),await this.substrate.relinquishCertificate(t,this.originator)}async discoverByIdentityKey(t){return await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(t,this.originator)}async discoverByAttributes(t){return 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 qe extends Ce{keyring;decryptedFields;constructor(t,e,i,r,n,s,a,o,c){super(t,e,i,r,n,s,o),this.keyring=a,this.decryptedFields=c}static fromCertificate(t,e){return new qe(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,e,t.signature)}async decryptFields(t,e,i){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 r={};for(const n in this.keyring){const{plaintext:s}=await t.decrypt({ciphertext:W(this.keyring[n],"base64"),...Ce.getCertificateFieldEncryptionDetails(n,this.serialNumber),counterparty:this.subject,privileged:e,privilegedReason:i}),a=new Kt(s).decrypt(W(this.fields[n],"base64"));r[n]=X(a)}return r}catch(t){throw new Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(t instanceof Error?t.message:t)}`)}}}class He{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 Ue(t,e,i="self"){const r=W(t,"base64"),n=r.slice(0,16),s=r.slice(16),{valid:a}=await e.verifyHmac({data:n,hmac:s,protocolID:[2,"server hmac"],keyID:X(n),counterparty:i});return a}async function Ke(t,e="self"){const i=yt(16),{hmac:r}=await t.createHmac({protocolID:[2,"server hmac"],keyID:X(i),data:i,counterparty:e});return J([...i,...r])}const $e=async(t,e,i)=>{const r=await t.listCertificates({certifiers:e.certifiers,types:Object.keys(e.types)});return await Promise.all(r.certificates.map((async r=>{const{keyringForVerifier:n}=await t.proveCertificate({certificate:r,fieldsToReveal:e.types[r.type],verifier:i});return new qe(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,n,r.signature)})))},We=async(t,e,i)=>{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 r=>{if(r.subject!==e.identityKey)throw new Error(`The subject of one of your certificates ("${r.subject}") is not the same as the request sender ("${e.identityKey}").`);const n=new qe(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,r.keyring,r.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)})))},ze="0.1";class je{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;constructor(t,e,i,r,n){this.wallet=t,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 He,this.autoPersistLastSession=!1!==n}async toPeer(t,e,i){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof e&&(e=this.lastInteractedWithPeer);const r=await this.getAuthenticatedSession(e,i),n=J(yt(32)),{signature:s}=await this.wallet.createSignature({data:t,protocolID:[2,"auth message signature"],keyID:`${n} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey}),a={version:ze,messageType:"general",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:n,yourNonce:r.peerNonce,payload:t,signature:s};r.lastUpdate=Date.now(),this.sessionManager.updateSession(r);try{await this.transport.send(a)}catch(t){const e=new Error(`Failed to send message to peer ${r.peerIdentityKey??"unknown"}: ${String(t.message)}`);throw e.stack=t.stack,e}}async requestCertificates(t,e,i=1e4){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof e&&(e=this.lastInteractedWithPeer);const r=await this.getAuthenticatedSession(e,i),n=J(yt(32)),{signature:s}=await this.wallet.createSignature({data:W(JSON.stringify(t),"utf8"),protocolID:[2,"auth message signature"],keyID:`${n} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey}),a={version:ze,messageType:"certificateRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:n,initialNonce:r.sessionNonce,yourNonce:r.peerNonce,requestedCertificates:t,signature:s};r.lastUpdate=Date.now(),this.sessionManager.updateSession(r);try{await this.transport.send(a)}catch(t){throw new Error(`Failed to send certificate request message to peer ${r.peerIdentityKey??"unknown"}: ${String(t.message)}`)}}async getAuthenticatedSession(t,e){if(void 0===this.transport)throw new Error("Peer transport is not connected!");let i;if("string"==typeof t&&(i=this.sessionManager.getSession(t)),null==i||!i.isAuthenticated){const r=await this.initiateHandshake(t,e);if(i=this.sessionManager.getSession(r),null==i||!i.isAuthenticated)throw new Error("Unable to establish mutual authentication with peer!")}return i}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,e=1e4){const i=await Ke(this.wallet),r=Date.now();this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:i,peerIdentityKey:t,lastUpdate:r});const n={version:ze,messageType:"initialRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,initialNonce:i,requestedCertificates:this.certificatesToRequest};return await this.transport.send(n),await this.waitForInitialResponse(i,e)}async waitForInitialResponse(t,e=1e4){return await new Promise(((i,r)=>{const n=this.listenForInitialResponse(t,(t=>{clearTimeout(s),this.stopListeningForInitialResponses(n),i(t)})),s=setTimeout((()=>{this.stopListeningForInitialResponses(n),r(new Error("Initial response timed out."))}),e)}))}listenForInitialResponse(t,e){const i=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(i,{callback:e,sessionNonce:t}),i}stopListeningForInitialResponses(t){this.onInitialResponseReceivedCallbacks.delete(t)}async handleIncomingMessage(t){if("string"!=typeof t.version||t.version!==ze)throw new Error(`Invalid or unsupported message auth version! Received: ${t.version}, expected: ${ze}`);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 Ke(this.wallet),i=Date.now();let r;this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:e,peerNonce:t.initialNonce,peerIdentityKey:t.identityKey,lastUpdate:i}),null!=t.requestedCertificates&&Array.isArray(t.requestedCertificates.certifiers)&&t.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach((e=>{e(t.identityKey,t.requestedCertificates)})):r=await $e(this.wallet,t.requestedCertificates,t.identityKey));const{signature:n}=await this.wallet.createSignature({data:W(t.initialNonce+e,"base64"),protocolID:[2,"auth message signature"],keyID:`${t.initialNonce} ${e}`,counterparty:t.identityKey}),s={version:ze,messageType:"initialResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,initialNonce:e,yourNonce:t.initialNonce,certificates:r,requestedCertificates:this.certificatesToRequest,signature:n};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=t.identityKey),await this.transport.send(s)}async processInitialResponse(t){if(!await Ue(t.yourNonce,this.wallet))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=W((e.sessionNonce??"")+(t.initialNonce??""),"base64"),{valid:r}=await this.wallet.verifySignature({data:i,signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${e.sessionNonce??""} ${t.initialNonce??""}`,counterparty:t.identityKey});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.lastUpdate=Date.now(),this.sessionManager.updateSession(e),this.certificatesToRequest?.certifiers?.length>0&&t.certificates?.length>0&&(await We(this.wallet,t,this.certificatesToRequest),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 $e(this.wallet,t.requestedCertificates,t.identityKey);await this.sendCertificateResponse(t.identityKey,e)}}async processCertificateRequest(t){if(!await Ue(t.yourNonce,this.wallet))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:W(JSON.stringify(t.requestedCertificates),"utf8"),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:e.peerIdentityKey});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 $e(this.wallet,t.requestedCertificates,t.identityKey);await this.sendCertificateResponse(t.identityKey,e)}}async sendCertificateResponse(t,e){const i=await this.getAuthenticatedSession(t),r=J(yt(32)),{signature:n}=await this.wallet.createSignature({data:W(JSON.stringify(e),"utf8"),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey}),s={version:ze,messageType:"certificateResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,certificates:e,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(t){const e=t instanceof Error?t.message:String(t);throw new Error(`Failed to send certificate response message to peer ${i.peerIdentityKey??"unknown"}: ${e}`)}}async processCertificateResponse(t){if(!await Ue(t.yourNonce,this.wallet))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:W(JSON.stringify(t.certificates),"utf8"),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:t.identityKey});if(!i)throw new Error(`Unable to verify certificate response signature for peer: ${t.identityKey}`);await We(this.wallet,t,t.requestedCertificates),this.onCertificatesReceivedCallbacks.forEach((e=>{e(t.identityKey,t.certificates??[])})),e.lastUpdate=Date.now(),this.sessionManager.updateSession(e)}async processGeneralMessage(t){if(!await Ue(t.yourNonce,this.wallet))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{valid:i}=await this.wallet.verifySignature({data:t.payload,signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:e.peerIdentityKey});if(!i)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??[])}))}}const Xe="undefined"!=typeof window?fetch.bind(window):fetch;class Ge{onDataCallback;fetchClient;baseUrl;constructor(t,e=Xe){this.fetchClient=e,this.baseUrl=t}async send(t){if(!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 new Promise((async(e,i)=>{try{const i=this.fetchClient(`${this.baseUrl}/.well-known/auth`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});"initialRequest"!==t.messageType&&e();const r=await i;if(!r.ok||!this.onDataCallback)throw new Error("HTTP server failed to authenticate");{const t=await r.json();this.onDataCallback(t)}"initialRequest"===t.messageType&&e()}catch(t){return void i(t)}}));{const e=this.deserializeRequestPayload(t.payload),i=`${this.baseUrl}${e.urlPostfix}`;let 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"]=$(t.signature),r.headers["x-bsv-auth-request-id"]=e.requestId,r.body){const t=r.headers;if(!t["content-type"])throw new Error("Content-Type header is required for requests with a body.");const e=t["content-type"];e.includes("application/json")||e.includes("application/x-www-form-urlencoded")||e.includes("text/plain")?r.body=X(r.body):r.body=new Uint8Array(r.body)}const n=await this.fetchClient(i,{method:r.method,headers:r.headers,body:r.body});if(500===n.status&&null==n.headers.get("x-bsv-auth-request-id")&&null==n.headers.get("x-bsv-auth-requested-certificates")){const t=await n.json();throw new Error(`HTTP ${n.status} - ${JSON.stringify(t)}`)}const s=await n.arrayBuffer(),a=new it;null!=n.headers.get("x-bsv-auth-request-id")&&a.write(W(n.headers.get("x-bsv-auth-request-id"),"base64")),a.writeVarIntNum(n.status);const o=[];n.headers.forEach(((t,e)=>{const i=e.toLowerCase();!i.startsWith("x-bsv-")&&"authorization"!==i||i.startsWith("x-bsv-auth")||o.push([i,t])})),o.sort((([t],[e])=>t.localeCompare(e))),a.writeVarIntNum(o.length);for(let t=0;t<o.length;t++){const e=W(o[t][0],"utf8");a.writeVarIntNum(e.length),a.write(e);const i=W(o[t][1],"utf8");a.writeVarIntNum(i.length),a.write(i)}if(s){const t=Array.from(new Uint8Array(s));a.writeVarIntNum(t.length),a.write(t)}else a.writeVarIntNum(-1);const c={version:n.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===n.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:n.headers.get("x-bsv-auth-identity-key"),nonce:n.headers.get("x-bsv-auth-nonce"),yourNonce:n.headers.get("x-bsv-auth-your-nonce"),requestedCertificates:JSON.parse(n.headers.get("x-bsv-auth-requested-certificates")),payload:a.toArray(),signature:W(n.headers.get("x-bsv-auth-signature"),"hex")};if(!c.version)throw new Error("HTTP server failed to authenticate");this.onDataCallback(c)}}async onData(t){this.onDataCallback=e=>{t(e)}}deserializeRequestPayload(t){const e=new rt(t),i=J(e.read(32)),r=e.readVarIntNum();let n="GET";r>0&&(n=X(e.read(r)));const s=e.readVarIntNum();let a="";s>0&&(a=X(e.read(s)));const o=e.readVarIntNum();let c="";o>0&&(c=X(e.read(o)));const h={},d=e.readVarIntNum();if(d>0)for(let t=0;t<d;t++){const t=e.readVarIntNum(),i=e.read(t),r=X(i),n=e.readVarIntNum(),s=e.read(n),a=X(s);h[r]=a}let u;const l=e.readVarIntNum();return l>0&&(u=e.read(l)),{urlPostfix:a+c,method:n,headers:h,body:u,requestId:i}}}class Je{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;peers={};constructor(t,e,i){this.wallet=t,this.requestedCertificates=e,this.sessionManager=i||new He}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:n="GET",headers:s={},body:a}=e,o=new URL(t),c=o.origin;let h;if(void 0===this.peers[c]){const t=new Ge(c);h={peer:new je(this.wallet,t,this.requestedCertificates,this.sessionManager),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 $e(this.wallet,e,t);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 d=yt(32),u=J(d),l=await this.serializeRequest(n,s,a,o,d);this.callbacks[u]={resolve:i,reject:r};const f=h.peer.listenForGeneralMessages(((t,e)=>{const i=new rt(e);if(J(i.read(32))!==u)return;h.peer.stopListeningForGeneralMessages(f),this.peers[c].identityKey=t,this.peers[c].supportsMutualAuth=!0;const r=i.readVarIntNum(),n={},s=i.readVarIntNum();if(s>0)for(let t=0;t<s;t++){const t=i.readVarIntNum(),e=i.read(t),r=X(e),s=i.readVarIntNum(),a=i.read(s),o=X(a);n[r]=o}let a;n["x-bsv-auth-identity-key"]=t;const o=i.readVarIntNum();o>0&&(a=i.read(o));const d=new Response(a?new Uint8Array(a):null,{status:r,statusText:`${r}`,headers:new Headers(n)});this.callbacks[u].resolve(d),delete this.callbacks[u]}));h.pendingCertificateRequests.length>0&&await new Promise((t=>{setInterval((()=>{0===h.pendingCertificateRequests.length&&t()}),100)})),await h.peer.toPeer(l.toArray(),h.identityKey).catch((async n=>{if(n.message.includes("Session not found for nonce")){delete this.peers[c],e.retryCounter??=3;const r=await this.fetch(t,e);i(r)}else if(n.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(n)}))}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 Ge(i);r={peer:new je(this.wallet,t,this.requestedCertificates,this.sessionManager)},this.peers[i]=r}return await new Promise((async(t,i)=>{const n=r.peer.listenForCertificatesReceived(((e,i)=>{r.peer.stopListeningForCertificatesReceived(n),this.certificatesReceived.push(...i),t(i)}));try{await r.peer.requestCertificates(e,r.identityKey)}catch(t){r.peer.stopListeningForCertificatesReceived(n),i(t)}}))}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(t,e,i,r,n){const s=new it;if(s.write(n),s.writeVarIntNum(t.length),s.write(W(t)),r.pathname.length>0){const t=W(r.pathname);s.writeVarIntNum(t.length),s.write(t)}else s.writeVarIntNum(-1);if(r.search.length>0){const t=W(r.search);s.writeVarIntNum(t.length),s.write(t)}else s.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))),s.writeVarIntNum(a.length);for(let t=0;t<a.length;t++){const e=W(a[t][0],"utf8");s.writeVarIntNum(e.length),s.write(e);const i=W(a[t][1],"utf8");s.writeVarIntNum(i.length),s.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);s.writeVarIntNum(t.length),s.write(t)}else s.writeVarIntNum(-1);return s}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 n=i.headers.get("x-bsv-payment-satoshis-required");if(!n)throw new Error("Missing x-bsv-payment-satoshis-required response header.");const s=parseInt(n);if(isNaN(s)||s<=0)throw new Error("Invalid x-bsv-payment-satoshis-required response header value.");const a=i.headers.get("x-bsv-auth-identity-key");if(!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.");const c=await Ke(this.wallet),{publicKey:h}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${o} ${c}`,counterparty:a}),d=(new ne).lock(bt.fromString(h).toAddress()).toHex(),{tx:u}=await this.wallet.createAction({description:`Payment for request to ${new URL(t).origin}`,outputs:[{satoshis:s,lockingScript:d,customInstructions:JSON.stringify({derivationPrefix:o,derivationSuffix:c,payee:a}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}});return e.headers=e.headers||{},e.headers["x-bsv-payment"]=JSON.stringify({derivationPrefix:o,derivationSuffix:c,transaction:J(u)}),e.retryCounter??=3,this.fetch(t,e)}async normalizeBodyToNumberArray(t){if(null==t)return[];if("object"==typeof t)return W(JSON.stringify(t,"utf8"));if(Array.isArray(t)&&t.every((t=>"number"==typeof t)))return t;if("string"==typeof t)return W(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 W(i,"utf8")}if(t instanceof URLSearchParams)return W(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 Ye{pushDrop;static decode(t){const e=ae.decode(t);if(e.fields.length<4)throw new Error("Invalid SHIP/SLAP advertisement!");const i=X(e.fields[0]);if("SHIP"!==i&&"SLAP"!==i)throw new Error("Invalid protocol type!");return{protocol:i,identityKey:$(e.fields[1]),domain:X(e.fields[2]),topicOrService:X(e.fields[3])}}constructor(t){this.pushDrop=new ae(t)}async lock(t,e,i){const{publicKey:r}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([W(t,"utf8"),W(r,"hex"),W(e,"utf8"),W(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 Ze=["https://users.bapp.dev"],Qe=["https://testnet-users.bapp.dev"];class ti{fetchClient;allowHTTP;constructor(t=fetch,e=!1){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=new Promise(((t,e)=>setTimeout((()=>e(new Error("Request timed out"))),i))),n=fetch(`${t}/lookup`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:e.service,query:e.query})}),s=await Promise.race([n,r]);if(s.ok)return await s.json();throw new Error("Failed to facilitate lookup")}}class ei{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;constructor(t={}){this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new ti(void 0,"local"===this.networkPreset),this.slapTrackers=t.slapTrackers??("mainnet"===this.networkPreset?Ze:Qe),this.hostOverrides=t.hostOverrides??{},this.additionalHosts=t.additionalHosts??{}}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.findCompetentHosts(t.service),this.additionalHosts[t.service]?.length>0&&(i=[...i,...this.additionalHosts[t.service]]),i.length<1)throw new Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${t.service}`);const r=(await Promise.allSettled(i.map((async i=>await this.facilitator.lookup(i,t,e))))).filter((t=>"fulfilled"===t.status)).map((t=>t.value));if(0===r.length)throw new Error("No successful responses from any hosts");const n=new Map;for(const t of r)if("output-list"===t.type)try{for(const e of t.outputs)try{const t=`${_e.fromBEEF(e.beef).id("hex")}.${e.outputIndex}`;n.set(t,e)}catch{continue}}catch(t){}return{type:"output-list",outputs:Array.from(n.values())}}async findCompetentHosts(t){const e={service:"ls_slap",query:{service:t}},i=await Promise.allSettled(this.slapTrackers.map((async t=>await this.facilitator.lookup(t,e,5e3)))),r=new Set;for(const e of i)if("fulfilled"===e.status){const i=e.value;if("output-list"!==i.type)continue;for(const e of i.outputs)try{const i=_e.fromBEEF(e.beef).outputs[e.outputIndex].lockingScript,n=Ye.decode(i);if(n.topicOrService!==t||"SLAP"!==n.protocol)continue;r.add(n.domain)}catch{continue}}return[...r]}}class ii{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 it;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 n=await fetch(`${t}/submit`,{method:"POST",headers:i,body:r});if(n.ok)return await n.json();throw new Error("Failed to facilitate broadcast")}}class ri{topics;facilitator;resolver;requireAcknowledgmentFromAllHostsForTopics;requireAcknowledgmentFromAnyHostForTopics;requireAcknowledgmentFromSpecificHostsForTopics;networkPreset;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 ii(void 0,"local"===this.networkPreset),this.resolver=e.resolver??new ei({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=e.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=e.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=e.requireAcknowledgmentFromSpecificHostsForTopics??{}}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 n=Object.entries(r).map((async([t,r])=>{try{const n=await this.facilitator.send(t,{beef:e,offChainValues:i,topics:[...r]});if(null==n||0===Object.keys(n).length)throw new Error("Steak has no topics.");return{host:t,success:!0,steak:n}}catch(e){return console.error(e),{host:t,success:!1,error:e}}})),s=(await Promise.all(n)).filter((t=>t.success));if(0===s.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 s){const e=t.host,i=t.steak,r=new Set;for(const[t,e]of Object.entries(i)){const i=e.outputsToAdmit,n=e.coinsToRetain,s=e.coinsRemoved;(i?.length>0||n?.length>0||s?.length>0)&&r.add(t)}a[e]=r}let o,c,h,d;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,d="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(h=this.topics,d="any"):Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?(h=this.requireAcknowledgmentFromAnyHostForTopics,d="all"):(h=[],d="all"),h.length>0&&!this.checkAcknowledgmentFromAnyHost(a,h,d)?{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 ${s.length} Overlay Services ${1===s.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 n,s;if("all"===r||"any"===r)s=r,n=this.topics;else{if(!Array.isArray(r))continue;n=r,s="all"}if("all"===s){for(const t of n)if(!e.has(t))return!1}else if("any"===s){let t=!1;for(const i of n)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={},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=_e.fromBEEF(i.beef).outputs[i.outputIndex].lockingScript,r=Ye.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 ni=Object.create(null);ni.open="0",ni.close="1",ni.ping="2",ni.pong="3",ni.message="4",ni.upgrade="5",ni.noop="6";const si=Object.create(null);Object.keys(ni).forEach((t=>{si[ni[t]]=t}));const ai={type:"error",data:"parser error"},oi="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),ci="function"==typeof ArrayBuffer,hi=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,di=({type:t,data:e},i,r)=>oi&&e instanceof Blob?i?r(e):ui(e,r):ci&&(e instanceof ArrayBuffer||hi(e))?i?r(e):ui(new Blob([e]),r):r(ni[t]+(e||"")),ui=(t,e)=>{const i=new FileReader;return i.onload=function(){const t=i.result.split(",")[1];e("b"+(t||""))},i.readAsDataURL(t)};function li(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let fi;const pi="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)pi["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const bi="function"==typeof ArrayBuffer,gi=(t,e)=>{if("string"!=typeof t)return{type:"message",data:yi(t,e)};const i=t.charAt(0);return"b"===i?{type:"message",data:mi(t.substring(1),e)}:si[i]?t.length>1?{type:si[i],data:t.substring(1)}:{type:si[i]}:ai},mi=(t,e)=>{if(bi){const i=(t=>{let e,i,r,n,s,a=.75*t.length,o=t.length,c=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);const h=new ArrayBuffer(a),d=new Uint8Array(h);for(e=0;e<o;e+=4)i=pi[t.charCodeAt(e)],r=pi[t.charCodeAt(e+1)],n=pi[t.charCodeAt(e+2)],s=pi[t.charCodeAt(e+3)],d[c++]=i<<2|r>>4,d[c++]=(15&r)<<4|n>>2,d[c++]=(3&n)<<6|63&s;return h})(t);return yi(i,e)}return{base64:!0,data:t}},yi=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,wi=String.fromCharCode(30);let Ii;function ki(t){return t.reduce(((t,e)=>t+e.length),0)}function vi(t,e){if(t[0].length===e)return t.shift();const i=new Uint8Array(e);let r=0;for(let n=0;n<e;n++)i[n]=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 _i(t){if(t)return function(t){for(var e in _i.prototype)t[e]=_i.prototype[e];return t}(t)}_i.prototype.on=_i.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},_i.prototype.once=function(t,e){function i(){this.off(t,i),e.apply(this,arguments)}return i.fn=e,this.on(t,i),this},_i.prototype.off=_i.prototype.removeListener=_i.prototype.removeAllListeners=_i.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 n=0;n<r.length;n++)if((i=r[n])===e||i.fn===e){r.splice(n,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},_i.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 n=(i=i.slice(0)).length;r<n;++r)i[r].apply(this,e)}return this},_i.prototype.emitReserved=_i.prototype.emit,_i.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},_i.prototype.hasListeners=function(t){return!!this.listeners(t).length};const Ei="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),Si="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Pi(t,...e){return e.reduce(((e,i)=>(t.hasOwnProperty(i)&&(e[i]=t[i]),e)),{})}const Oi=Si.setTimeout,Ni=Si.clearTimeout;function Ai(t,e){e.useNativeTimers?(t.setTimeoutFn=Oi.bind(Si),t.clearTimeoutFn=Ni.bind(Si)):(t.setTimeoutFn=Si.setTimeout.bind(Si),t.clearTimeoutFn=Si.clearTimeout.bind(Si))}function xi(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Ti extends Error{constructor(t,e,i){super(t),this.description=e,this.context=i,this.type="TransportError"}}class Ci extends _i{constructor(t){super(),this.writable=!1,Ai(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 Ti(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=gi(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 Ri extends Ci{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(wi),r=[];for(let t=0;t<i.length;t++){const n=gi(i[t],e);if(r.push(n),"error"===n.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 n=0;t.forEach(((t,s)=>{di(t,!1,(t=>{r[s]=t,++n===i&&e(r.join(wi))}))}))})(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]=xi()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let Fi=!1;try{Fi="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const Bi=Fi;function Li(){}class Di extends Ri{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 Mi extends _i{constructor(t,e,i){super(),this.createRequest=t,Ai(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=Pi(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=Mi.requestsCount++,Mi.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=Li,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Mi.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 Vi(){for(let t in Mi.requests)Mi.requests.hasOwnProperty(t)&&Mi.requests[t].abort()}Mi.requestsCount=0,Mi.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Vi):"function"==typeof addEventListener&&addEventListener("onpagehide"in Si?"pagehide":"unload",Vi,!1));const qi=function(){const t=Hi({xdomain:!1});return t&&null!==t.responseType}();function Hi(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||Bi))return new XMLHttpRequest}catch(t){}if(!e)try{return new(Si[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const Ui="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Ki extends Ci{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,i=Ui?{}:Pi(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;di(i,this.supportsBinary,(t=>{try{this.doWrite(i,t)}catch(t){}r&&Ei((()=>{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]=xi()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const $i=Si.WebSocket||Si.MozWebSocket,Wi={websocket:class extends Ki{createSocket(t,e,i){return Ui?new $i(t,e,i):e?new $i(t,e):new $i(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends Ci{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){Ii||(Ii=new TextDecoder);const i=[];let r=0,n=-1,s=!1;return new TransformStream({transform(a,o){for(i.push(a);;){if(0===r){if(ki(i)<1)break;const t=vi(i,1);s=!(128&~t[0]),n=127&t[0],r=n<126?3:126===n?1:2}else if(1===r){if(ki(i)<2)break;const t=vi(i,2);n=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),r=3}else if(2===r){if(ki(i)<8)break;const t=vi(i,8),e=new DataView(t.buffer,t.byteOffset,t.length),s=e.getUint32(0);if(s>Math.pow(2,21)-1){o.enqueue(ai);break}n=s*Math.pow(2,32)+e.getUint32(4),r=3}else{if(ki(i)<n)break;const t=vi(i,n);o.enqueue(gi(s?t:Ii.decode(t),e)),r=0}if(0===n||n>t){o.enqueue(ai);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=t.readable.pipeThrough(e).getReader(),r=new TransformStream({transform(t,e){!function(t,e){oi&&t.data instanceof Blob?t.data.arrayBuffer().then(li).then(e):ci&&(t.data instanceof ArrayBuffer||hi(t.data))?e(li(t.data)):di(t,!1,(t=>{fi||(fi=new TextEncoder),e(fi.encode(t))}))}(t,(i=>{const r=i.length;let n;if(r<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,r);else if(r<65536){n=new Uint8Array(3);const t=new DataView(n.buffer);t.setUint8(0,126),t.setUint16(1,r)}else{n=new Uint8Array(9);const t=new DataView(n.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(r))}t.data&&"string"!=typeof t.data&&(n[0]|=128),e.enqueue(n),e.enqueue(i)}))}});r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const n=()=>{i.read().then((({done:t,value:e})=>{t||(this.onPacket(e),n())})).catch((t=>{}))};n();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this._writer.write(s).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&&Ei((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends Di{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=qi&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Mi(Hi,this.uri(),t)}}},zi=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ji=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Xi(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 n=zi.exec(t||""),s={},a=14;for(;a--;)s[ji[a]]=n[a]||"";return-1!=i&&-1!=r&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.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,s.path),s.queryKey=function(t,e){const i={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,r){e&&(i[e]=r)})),i}(0,s.query),s}const Gi="function"==typeof addEventListener&&"function"==typeof removeEventListener,Ji=[];Gi&&addEventListener("offline",(()=>{Ji.forEach((t=>t()))}),!1);class Yi extends _i{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=Xi(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=Xi(e.host).host);Ai(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)),Gi&&(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"})},Ji.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&&Yi.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",Yi.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 i=0;i<this.writeBuffer.length;i++){const r=this.writeBuffer[i].data;if(r&&(t+="string"==typeof(e=r)?function(t){let e=0,i=0;for(let r=0,n=t.length;r<n;r++)e=t.charCodeAt(r),e<128?i+=1:e<2048?i+=2:e<55296||e>=57344?i+=3:(r++,i+=4);return i}(e):Math.ceil(1.33*(e.byteLength||e.size))),i>0&&t>this._maxPayload)return this.writeBuffer.slice(0,i);t+=2}var e;return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Ei((()=>{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 n={type:t,data:e,options:i};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),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(Yi.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(),Gi&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=Ji.indexOf(this._offlineEventListener);-1!==t&&Ji.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}Yi.protocol=4;class Zi extends Yi{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;Yi.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;Yi.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 n(){i||(i=!0,h(),e.close(),e=null)}const s=t=>{const i=new Error("probe error: "+t);i.transport=e.name,n(),this.emitReserved("upgradeError",i)};function a(){s("transport closed")}function o(){s("socket closed")}function c(t){e&&t.name!==e.name&&n()}const h=()=>{e.removeListener("open",r),e.removeListener("error",s),e.removeListener("close",a),this.off("close",o),this.off("upgrading",c)};e.once("open",r),e.once("error",s),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 Qi extends Zi{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=>Wi[t])).filter((t=>!!t))),super(t,i)}}const tr="function"==typeof ArrayBuffer,er=Object.prototype.toString,ir="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===er.call(Blob),rr="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===er.call(File);function nr(t){return tr&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||ir&&t instanceof Blob||rr&&t instanceof File}function sr(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,i=t.length;e<i;e++)if(sr(t[e]))return!0;return!1}if(nr(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return sr(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&sr(t[e]))return!0;return!1}function ar(t){const e=[],i=t.data,r=t;return r.data=or(i,e),r.attachments=e.length,{packet:r,buffers:e}}function or(t,e){if(!t)return t;if(nr(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]=or(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]=or(t[r],e));return i}return t}function cr(t,e){return t.data=hr(t.data,e),delete t.attachments,t}function hr(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]=hr(t[i],e);else if("object"==typeof t)for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=hr(t[i],e));return t}const dr=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],ur=5;var lr;!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"}(lr||(lr={}));class fr{constructor(t){this.replacer=t}encode(t){return t.type!==lr.EVENT&&t.type!==lr.ACK||!sr(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===lr.EVENT?lr.BINARY_EVENT:lr.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==lr.BINARY_EVENT&&t.type!==lr.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=ar(t),i=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(i),r}}function pr(t){return"[object Object]"===Object.prototype.toString.call(t)}class br extends _i{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===lr.BINARY_EVENT;i||e.type===lr.BINARY_ACK?(e.type=i?lr.EVENT:lr.ACK,this.reconstructor=new gr(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!nr(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===lr[i.type])throw new Error("unknown packet type "+i.type);if(i.type===lr.BINARY_EVENT||i.type===lr.BINARY_ACK){const r=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const n=t.substring(r,e);if(n!=Number(n)||"-"!==t.charAt(e))throw new Error("Illegal attachments");i.attachments=Number(n)}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(!br.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 lr.CONNECT:return pr(e);case lr.DISCONNECT:return void 0===e;case lr.CONNECT_ERROR:return"string"==typeof e||pr(e);case lr.EVENT:case lr.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===dr.indexOf(e[0]));case lr.ACK:case lr.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class gr{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=cr(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function mr(t,e,i){return t.on(e,i),function(){t.off(e,i)}}const yr=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class wr extends _i{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=[mr(t,"open",this.onopen.bind(this)),mr(t,"packet",this.onpacket.bind(this)),mr(t,"error",this.onerror.bind(this)),mr(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,n;if(yr.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 s={type:lr.EVENT,data:e,options:{}};if(s.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,i=e.pop();this._registerAckCallback(t,i),s.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===(n=this.io.engine)||void 0===n?void 0:n._hasPingExpired());return this.flags.volatile&&!a||(o?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),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 n=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),s=(...t)=>{this.io.clearTimeoutFn(n),e.apply(this,t)};s.withError=!0,this.acks[t]=s}emitWithAck(t,...e){return new Promise(((i,r)=>{const n=(t,e)=>t?r(t):i(e);n.withError=!0,e.push(n),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:lr.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 lr.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 lr.EVENT:case lr.BINARY_EVENT:this.onevent(t);break;case lr.ACK:case lr.BINARY_ACK:this.onack(t);break;case lr.DISCONNECT:this.ondisconnect();break;case lr.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:lr.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:lr.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 Ir(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}Ir.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)},Ir.prototype.reset=function(){this.attempts=0},Ir.prototype.setMin=function(t){this.ms=t},Ir.prototype.setMax=function(t){this.max=t},Ir.prototype.setJitter=function(t){this.jitter=t};class kr extends _i{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,Ai(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 Ir({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const n=e.parser||i;this.encoder=new n.Encoder,this.decoder=new n.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 Qi(this.uri,this.opts);const e=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const r=mr(e,"open",(function(){i.onopen(),t&&t()})),n=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},s=mr(e,"error",n);if(!1!==this._timeout){const t=this._timeout,i=this.setTimeoutFn((()=>{r(),n(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(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(mr(t,"ping",this.onping.bind(this)),mr(t,"data",this.ondata.bind(this)),mr(t,"error",this.onerror.bind(this)),mr(t,"close",this.onclose.bind(this)),mr(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){Ei((()=>{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 wr(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 vr={};function _r(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=Xi(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 n=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+n+":"+r.port+e,r.href=r.protocol+"://"+n+(i&&i.port===r.port?"":":"+r.port),r}(t,(e=e||{}).path||"/socket.io"),r=i.source,n=i.id,s=i.path,a=vr[n]&&s in vr[n].nsps;let o;return e.forceNew||e["force new connection"]||!1===e.multiplex||a?o=new kr(r,e):(vr[n]||(vr[n]=new kr(r,e)),o=vr[n]),i.query&&!e.query&&(e.query=i.queryKey),o.socket(i.path,e)}Object.assign(_r,{Manager:kr,Socket:wr,io:_r,connect:_r});class Er{socket;onDataCallback;constructor(t){this.socket=t,this.socket.on("authMessage",(async t=>{this.onDataCallback&&await this.onDataCallback(t)}))}async send(t){this.socket.emit("authMessage",t)}async onData(t){this.onDataCallback=t}}class Sr{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 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(i)for(const t of i)t(e)}encodeEventPayload(t,e){const i={eventName:t,data:e};return W(JSON.stringify(i),"utf8")}decodeEventPayload(t){try{const e=X(t);return JSON.parse(e)}catch{return{eventName:"_unknown",data:void 0}}}}class Pr{static isEnabled=!1;static enable(){this.isEnabled=!0}static disable(){this.isEnabled=!1}static log(...t){this.isEnabled&&console.log(...t)}static warn(...t){this.isEnabled&&console.warn(...t)}static error(...t){console.error(...t)}}class Or{host;authFetch;walletClient;socket;myIdentityKey;joinedRooms=new Set;lookupResolver;networkPreset;initialized=!1;constructor(t={}){const{host:e,walletClient:i,enableLogging:r=!1,networkPreset:n="mainnet"}=t,s="testnet"===this.networkPreset?"https://staging-messagebox.babbage.systems":"https://messagebox.babbage.systems";this.host=e?.trim()??s,this.walletClient=i??new Ve,this.authFetch=new Je(this.walletClient),this.networkPreset=n,this.lookupResolver=new ei({networkPreset:n}),r&&Pr.enable()}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){Pr.log("[MB CLIENT] Anointing host:",e);const{txid:t}=await this.anointHost(e);if(null==t||""===t.trim())throw new Error("Failed to anoint host: No transaction ID returned")}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;Pr.log("[MB CLIENT] Fetching identity key...");try{const t=await this.walletClient.getPublicKey({identityKey:!0});return this.myIdentityKey=t.publicKey,Pr.log(`[MB CLIENT] Identity key fetched: ${this.myIdentityKey}`),this.myIdentityKey}catch(t){throw Pr.error("[MB CLIENT ERROR] Failed to fetch identity key:",t),new Error("Identity key retrieval failed")}}get testSocket(){return this.socket}async initializeConnection(){if(await this.assertInitialized(),Pr.log("[MB CLIENT] initializeConnection() STARTED"),null==this.myIdentityKey||""===this.myIdentityKey.trim()){Pr.log("[MB CLIENT] Fetching identity key...");try{const t=await this.walletClient.getPublicKey({identityKey:!0});this.myIdentityKey=t.publicKey,Pr.log(`[MB CLIENT] Identity key fetched successfully: ${this.myIdentityKey}`)}catch(t){throw Pr.error("[MB CLIENT ERROR] Failed to fetch identity key:",t),new Error("Identity key retrieval failed")}}if(null==this.myIdentityKey||""===this.myIdentityKey.trim())throw Pr.error("[MB CLIENT ERROR] Identity key is still missing after retrieval!"),new Error("Identity key is missing");if(Pr.log("[MB CLIENT] Setting up WebSocket connection..."),null==this.socket){if("string"!=typeof this.host||""===this.host.trim())throw new Error("Cannot initialize WebSocket: Host is not set");this.socket=function(t,e){const i=_r(t,e.managerOptions),r=new Er(i),n=new je(e.wallet,r,e.requestedCertificates,e.sessionManager);return new Sr(i,n)}(this.host,{wallet:this.walletClient});let t=!1,e=!1;this.socket.on("connect",(()=>{Pr.log("[MB CLIENT] Connected to WebSocket."),t||(Pr.log("[MB CLIENT] Sending authentication data:",this.myIdentityKey),null==this.myIdentityKey||""===this.myIdentityKey.trim()?Pr.error("[MB CLIENT ERROR] Cannot send authentication: Identity key is missing!"):(this.socket?.emit("authenticated",{identityKey:this.myIdentityKey}),t=!0))})),this.socket.on("authenticationSuccess",(t=>{Pr.log(`[MB CLIENT] WebSocket authentication successful: ${JSON.stringify(t)}`),e=!0})),this.socket.on("authenticationFailed",(t=>{Pr.error(`[MB CLIENT ERROR] WebSocket authentication failed: ${JSON.stringify(t)}`),e=!1})),this.socket.on("disconnect",(()=>{Pr.log("[MB CLIENT] Disconnected from MessageBox server"),this.socket=void 0,t=!1,e=!1})),this.socket.on("error",(t=>{Pr.error("[MB CLIENT ERROR] WebSocket error:",t)})),await new Promise(((t,i)=>{setTimeout((()=>{e?(Pr.log("[MB CLIENT] WebSocket fully authenticated and ready!"),t()):i(new Error("[MB CLIENT ERROR] WebSocket authentication timed out!"))}),5e3)}))}}async resolveHostForRecipient(t){const e=await this.queryAdvertisements(t);return 0===e.length?(Pr.warn(`[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 n=await this.lookupResolver.query({service:"ls_messagebox",query:r});if("output-list"!==n.type)throw new Error(`Unexpected result type: ${n.type}`);for(const t of n.outputs)try{const e=_e.fromBEEF(t.beef),r=e.outputs[t.outputIndex].lockingScript,n=ae.decode(r),[,s]=n.fields;if(null==s||0===s.length)throw new Error("Empty host field");i.push({host:X(s),txid:e.id("hex"),outputIndex:t.outputIndex,lockingScript:r,beef:t.beef})}catch{}}catch(t){Pr.error("[MB CLIENT ERROR] _queryAdvertisements failed:",t)}return i}async joinRoom(t){if(await this.assertInitialized(),Pr.log(`[MB CLIENT] Attempting to join WebSocket room: ${t}`),null==this.socket&&(Pr.log("[MB CLIENT] No WebSocket connection. Initializing..."),await this.initializeConnection()),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw new Error("[MB CLIENT ERROR] Identity key is not defined");const e=`${this.myIdentityKey??""}-${t}`;if(this.joinedRooms.has(e))Pr.log(`[MB CLIENT] Already joined WebSocket room: ${e}`);else try{Pr.log(`[MB CLIENT] Joining WebSocket room: ${e}`),await(this.socket?.emit("joinRoom",e)),this.joinedRooms.add(e),Pr.log(`[MB CLIENT] Successfully joined room: ${e}`)}catch(t){Pr.error(`[MB CLIENT ERROR] Failed to join WebSocket room: ${e}`,t)}}async listenForLiveMessages({onMessage:t,messageBox:e}){if(await this.assertInitialized(),Pr.log(`[MB CLIENT] Setting up listener for WebSocket room: ${e}`),await this.joinRoom(e),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw new Error("[MB CLIENT ERROR] Identity key is missing. Cannot construct room ID.");const i=`${this.myIdentityKey}-${e}`;Pr.log(`[MB CLIENT] Listening for messages in room: ${i}`),this.socket?.on(`sendMessage-${i}`,(e=>{(async()=>{Pr.log(`[MB CLIENT] Received message in room ${i}:`,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){Pr.log(`[MB CLIENT] Decrypting message from ${String(e.sender)}...`);const i=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:e.sender,ciphertext:W(t.encryptedMessage,"base64")});e.body=X(i.plaintext)}else Pr.log("[MB CLIENT] Message is not encrypted."),e.body="string"==typeof t?t:(()=>{try{return JSON.stringify(t)}catch{return"[Error: Unstringifiable message]"}})()}catch(t){Pr.error("[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:n}){if(await this.assertInitialized(),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),null==this.socket||!this.socket.connected){Pr.warn("[MB CLIENT WARNING] WebSocket not connected, falling back to HTTP");const r=await this.resolveHostForRecipient(t);return await this.sendMessage({recipient:t,messageBox:e,body:i},r)}let s;try{const e=await this.walletClient.createHmac({data:Array.from((new TextEncoder).encode(JSON.stringify(i))),protocolID:[1,"messagebox"],keyID:"1",counterparty:t});s=r??Array.from(e.hmac).map((t=>t.toString(16).padStart(2,"0"))).join("")}catch(t){throw Pr.error("[MB CLIENT ERROR] Failed to generate HMAC:",t),new Error("Failed to generate message identifier.")}const a=`${t}-${e}`;let o;if(Pr.log(`[MB CLIENT] Sending WebSocket message to room: ${a}`),!0===n)o="string"==typeof i?i:JSON.stringify(i);else{const e=await this.walletClient.encrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t,plaintext:W("string"==typeof i?i:JSON.stringify(i),"utf8")});o=JSON.stringify({encryptedMessage:J(e.ciphertext)})}return await new Promise(((r,c)=>{const h=`sendMessageAck-${a}`;let d=!1;const u=a=>{if(d)return;d=!0;const o=this.socket;if("function"==typeof o?.off&&o.off(h,u),Pr.log("[MB CLIENT] Received WebSocket acknowledgment:",a),null==a||"success"!==a.status){Pr.warn("[MB CLIENT] WebSocket message failed or returned unexpected response. Falling back to HTTP.");const a={recipient:t,messageBox:e,body:i,messageId:s,skipEncryption:n};this.resolveHostForRecipient(t).then((async t=>await this.sendMessage(a,t))).then(r).catch(c)}else Pr.log("[MB CLIENT] Message sent successfully via WebSocket:",a),r(a)};this.socket?.on(h,u),this.socket?.emit("sendMessage",{roomId:a,message:{messageId:s,recipient:t,body:o}}),setTimeout((()=>{if(!d){d=!0;const a=this.socket;"function"==typeof a?.off&&a.off(h,u),Pr.warn("[CLIENT] WebSocket acknowledgment timed out, falling back to HTTP");const o={recipient:t,messageBox:e,body:i,messageId:s,skipEncryption:n};this.resolveHostForRecipient(t).then((async t=>await this.sendMessage(o,t))).then(r).catch(c)}}),1e4)}))}async leaveRoom(t){if(await this.assertInitialized(),null==this.socket)return void Pr.warn("[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}`;Pr.log(`[MB CLIENT] Leaving WebSocket room: ${e}`),this.socket.emit("leaveRoom",e),this.joinedRooms.delete(e)}async disconnectWebSocket(){await this.assertInitialized(),null!=this.socket?(Pr.log("[MB CLIENT] Closing WebSocket connection..."),this.socket.disconnect(),this.socket=void 0):Pr.log("[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;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});i=t.messageId??Array.from(e.hmac).map((t=>t.toString(16).padStart(2,"0"))).join("")}catch(t){throw Pr.error("[MB CLIENT ERROR] Failed to generate HMAC:",t),new Error("Failed to generate message identifier.")}if(!0===t.skipEncryption)r="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:W("string"==typeof t.body?t.body:JSON.stringify(t.body),"utf8")});r=JSON.stringify({encryptedMessage:J(e.ciphertext)})}const n={message:{...t,messageId:i,body:r}};try{const r=e??await this.resolveHostForRecipient(t.recipient);if(Pr.log("[MB CLIENT] Sending HTTP request to:",`${r}/sendMessage`),Pr.log("[MB CLIENT] Request Body:",JSON.stringify(n,null,2)),null==this.myIdentityKey||""===this.myIdentityKey)try{const t=await this.walletClient.getPublicKey({identityKey:!0});this.myIdentityKey=t.publicKey,Pr.log(`[MB CLIENT] Fetched identity key before sending request: ${this.myIdentityKey}`)}catch(t){throw Pr.error("[MB CLIENT ERROR] Failed to fetch identity key:",t),new Error("Identity key retrieval failed")}const s=await this.authFetch.fetch(`${r}/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(Pr.log("[MB CLIENT] Raw Response Body:",a),!s.ok)throw Pr.error(`[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 Pr.error(`[MB CLIENT ERROR] Server returned an error: ${String(a.description)}`),new Error(a.description??"Unknown error from server.");return Pr.log("[MB CLIENT] Message successfully sent."),{...a,messageId:i}}catch(t){Pr.error("[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 anointHost(t){Pr.log("[MB CLIENT] Starting anointHost...");try{if(!t.startsWith("http"))throw new Error("Invalid host URL");const e=await this.getIdentityKey();Pr.log("[MB CLIENT] Fields - Identity:",e,"Host:",t);const i=[W(e,"hex"),W(t,"utf8")],r=new ae(this.walletClient);Pr.log("Fields:",i.map((t=>$(t)))),Pr.log("ProtocolID:",[1,"messagebox advertisement"]),Pr.log("KeyID:","1"),Pr.log("SignAs:","self"),Pr.log("anyoneCanSpend:",!1),Pr.log("forSelf:",!0);const n=await r.lock(i,[1,"messagebox advertisement"],"1","anyone",!0);Pr.log("[MB CLIENT] PushDrop script:",n.toASM());const{tx:s,txid:a}=await this.walletClient.createAction({description:"Anoint host for overlay routing",outputs:[{basket:"overlay advertisements",lockingScript:n.toHex(),satoshis:1,outputDescription:"Overlay advertisement output"}],options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1}});if(Pr.log("[MB CLIENT] Transaction created:",a),void 0!==s){const t=new ri(["tm_messagebox"],{networkPreset:this.networkPreset}),e=await t.broadcast(_e.fromAtomicBEEF(s));if(Pr.log("[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 Pr.error("[MB CLIENT ERROR] anointHost threw:",t),t}}async revokeHostAdvertisement(t){Pr.log("[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"}]});if(void 0===i)throw new Error("Failed to create signable transaction.");const r=_e.fromBEEF(i.tx),n=new ae(this.walletClient),s=await n.unlock([1,"messagebox advertisement"],"1","anyone","all",!1,t.outputIndex,t.lockingScript),a=await s.sign(r,t.outputIndex),{tx:o}=await this.walletClient.signAction({reference:i.reference,spends:{[t.outputIndex]:{unlockingScript:a.toHex()}},options:{acceptDelayedBroadcast:!1}});if(void 0===o)throw new Error("Failed to finalize the transaction signature.");const c=new ri(["tm_messagebox"],{networkPreset:this.networkPreset}),h=await c.broadcast(_e.fromAtomicBEEF(o));if(Pr.log("[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 Pr.error("[MB CLIENT ERROR] revokeHost threw:",t),t}}async listMessages({messageBox:t,host:e}){if(await this.assertInitialized(),""===t.trim())throw new Error("MessageBox cannot be empty");let i=null!=e?[e]:[];if(0===i.length){const t=await this.queryAdvertisements(await this.getIdentityKey());i=Array.from(new Set([this.host,...t.map((t=>t.host))]))}const r=await Promise.allSettled(i.map((async e=>{try{Pr.log(`[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 Pr.log(`[MB CLIENT DEBUG] listMessages failed for ${e}:`,t),t}}))),n=[],s=[];for(const t of r)"fulfilled"===t.status?n.push(t.value):s.push(t.reason);if(0===n.length)throw new Error("Failed to retrieve messages from any host");const a=new Map;for(const t of n)for(const e of t)a.has(e.messageId)||a.set(e.messageId,e);if(0===a.size)return[];const o=t=>{try{return JSON.parse(t)}catch{return t}},c=Array.from(a.values());for(const t of c)try{const e="string"==typeof t.body?o(t.body):t.body;if(null!=e&&"object"==typeof e&&"string"==typeof e.encryptedMessage){Pr.log(`[MB CLIENT] Decrypting message from ${String(t.sender)}…`);const i=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t.sender,ciphertext:W(e.encryptedMessage,"base64")}),r=X(i.plaintext);t.body=o(r)}else t.body=e}catch(e){Pr.error("[MB CLIENT ERROR] Failed to parse or decrypt message in list:",e),t.body="[Error: Failed to decrypt or parse message]"}return c.sort(((t,e)=>Number(e.timestamp??0)-Number(t.timestamp??0))),c}async acknowledgeMessage({messageIds:t,host:e}){if(await this.assertInitialized(),!Array.isArray(t)||0===t.length)throw new Error("Message IDs array cannot be empty");Pr.log(`[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);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 Pr.log(`[MB CLIENT] Acknowledged on ${e}`),r.status}catch(t){return Pr.warn(`[MB CLIENT WARN] acknowledgeMessage failed for ${e}:`,t),null}}))),n=r.filter((t=>"fulfilled"===t.status)),s=n.find((t=>null!=t.value))?.value;if(null!=s)return s;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("; ")}`)}}function Nr(t){try{return"string"==typeof t?JSON.parse(t):t}catch(e){return Pr.error("[PP CLIENT] Failed to parse input in safeParse:",t),{}}}const Ar="payment_inbox";class xr extends Or{peerPayWalletClient;_authFetchInstance;constructor(t){const{messageBoxHost:e="https://messagebox.babbage.systems",walletClient:i,enableLogging:r=!1}=t;super({host:e,walletClient:i,enableLogging:r}),this.peerPayWalletClient=i}get authFetchInstance(){return null!==this._authFetchInstance&&void 0!==this._authFetchInstance||(this._authFetchInstance=new Je(this.peerPayWalletClient)),this._authFetchInstance}async createPaymentToken(t){if(t.amount<=0)throw new Error("Invalid payment details: recipient and valid amount are required");const e=await Ke(this.peerPayWalletClient),i=await Ke(this.peerPayWalletClient);Pr.log(`[PP CLIENT] Derivation Prefix: ${e}`),Pr.log(`[PP CLIENT] Derivation Suffix: ${i}`);const{publicKey:r}=await this.peerPayWalletClient.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${e} ${i}`,counterparty:t.recipient});if(Pr.log(`[PP CLIENT] Derived Public Key: ${r}`),null==r||""===r.trim())throw new Error("Failed to derive recipient’s public key");const n=(new ne).lock(bt.fromString(r).toAddress()).toHex();Pr.log(`[PP CLIENT] Locking Script: ${n}`);const s=await this.peerPayWalletClient.createAction({description:"PeerPay payment",outputs:[{satoshis:t.amount,lockingScript:n,customInstructions:JSON.stringify({derivationPrefix:e,derivationSuffix:i,payee:t.recipient}),outputDescription:"Payment for PeerPay transaction"}],options:{randomizeOutputs:!1}});if(void 0===s.tx)throw new Error("Transaction creation failed!");return Pr.log("[PP CLIENT] Payment Action:",s),{customInstructions:{derivationPrefix:e,derivationSuffix:i},transaction:s.tx,amount:t.amount}}async sendPayment(t){if(null==t.recipient||""===t.recipient.trim()||t.amount<=0)throw new Error("Invalid payment details: recipient and valid amount are required");const e=await this.createPaymentToken(t);await this.sendMessage({recipient:t.recipient,messageBox:Ar,body:JSON.stringify(e)})}async sendLivePayment(t){const e=await this.createPaymentToken(t);try{await this.sendLiveMessage({recipient:t.recipient,messageBox:Ar,body:JSON.stringify(e)})}catch(i){Pr.warn("[PP CLIENT] sendLiveMessage failed, falling back to HTTP:",i),await this.sendMessage({recipient:t.recipient,messageBox:Ar,body:JSON.stringify(e)})}}async listenForLivePayments({onPayment:t}){await this.listenForLiveMessages({messageBox:Ar,onMessage:e=>{Pr.log("[MB CLIENT] Received Live Payment:",e);const i={messageId:e.messageId,sender:e.sender,token:Nr(e.body)};Pr.log("[PP CLIENT] Converted PeerMessage to IncomingPayment:",i),t(i)}})}async acceptPayment(t){try{Pr.log(`[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:0,protocol:"wallet payment"}],description:"PeerPay Payment"});return Pr.log(`[PP CLIENT] Payment internalized successfully: ${JSON.stringify(e,null,2)}`),Pr.log(`[PP CLIENT] Acknowledging payment with messageId: ${t.messageId}`),await this.acknowledgeMessage({messageIds:[t.messageId]}),{payment:t,paymentResult:e}}catch(t){return Pr.error(`[PP CLIENT] Error accepting payment: ${String(t)}`),"Unable to receive payment!"}}async rejectPayment(t){if(Pr.log(`[PP CLIENT] Rejecting payment: ${JSON.stringify(t,null,2)}`),t.token.amount-1e3<1e3){Pr.log("[PP CLIENT] Payment amount too small after fee, just acknowledging.");try{Pr.log(`[PP CLIENT] Attempting to acknowledge message ${t.messageId}...`),null!==this.authFetch&&void 0!==this.authFetch||Pr.warn("[PP CLIENT] Warning: authFetch is undefined! Ensure PeerPayClient is initialized correctly."),Pr.log("[PP CLIENT] authFetch instance:",this.authFetch);const e=await this.acknowledgeMessage({messageIds:[t.messageId]});Pr.log(`[PP CLIENT] Acknowledgment response: ${e}`)}catch(t){if(null==t||"object"!=typeof t||!("message"in t)||"string"!=typeof t.message||!t.message.includes("401"))throw Pr.error(`[PP CLIENT] Error acknowledging message: ${t.message}`),t;Pr.warn(`[PP CLIENT] Authentication issue while acknowledging: ${t.message}`)}}else{Pr.log("[PP CLIENT] Accepting payment before refunding..."),await this.acceptPayment(t),Pr.log(`[PP CLIENT] Sending refund of ${t.token.amount-1e3} to ${t.sender}...`),await this.sendPayment({recipient:t.sender,amount:t.token.amount-1e3}),Pr.log("[PP CLIENT] Payment successfully rejected and refunded.");try{Pr.log(`[PP CLIENT] Acknowledging message ${t.messageId} after refunding...`),await this.acknowledgeMessage({messageIds:[t.messageId]}),Pr.log("[PP CLIENT] Acknowledgment after refund successful.")}catch(t){Pr.error(`[PP CLIENT] Error acknowledging message after refund: ${t.message}`)}}}async listIncomingPayments(){return(await this.listMessages({messageBox:Ar})).map((t=>{const e=Nr(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:()=>Nr,PeerPayClient:()=>Tr,STANDARD_PAYMENT_MESSAGEBOX:()=>xr});var i={};t.r(i),t.d(i,{Decoder:()=>gr,Encoder:()=>pr,PacketType:()=>fr,protocol:()=>lr});class r{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(r.wordSize);static WORD_MASK=(1n<<r.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&r.WORD_MASK)),e>>=r.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 n=t.length>0?t.length:1;for(let e=n-1;e>=0;e--){const n=void 0===t[e]?0:t[e];i=i<<r.WORD_SIZE_BIGINT|BigInt(n&Number(r.WORD_MASK))}this._magnitude=i,this._sign=e,this._nominalWordLength=n,this.normSign()}get length(){return Math.max(1,this._nominalWordLength)}static isBN(t){return t instanceof r||null!==t&&"object"==typeof t&&t.constructor?.wordSize===r.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,n=i;if("le"!==e&&"be"!==e||(n=e,r=10),"number"!=typeof t)if(Array.isArray(t))this.initArray(t,n);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,s=0;e.startsWith("-")?(i++,s=1):e.startsWith("+")&&i++;const a=e.substring(i);if(0===a.length)return this._initializeState(0n,1===s&&e.startsWith("-")?1:0),void this.normSign();if(16===r){let t;if("le"===n){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),n=parseInt(r,16);if(isNaN(n))throw new Error("Invalid character in "+e);t.push(n)}return this.initArray(t,"le"),this._sign=s,void this.normSign()}try{t=BigInt("0x"+a)}catch(t){throw new Error("Invalid character in "+a)}this._initializeState(t,s),this.normSign()}else try{if(this._parseBaseString(a,r),this._sign=s,this.normSign(),"le"===n){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,n)}_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 n=BigInt(e);for(;r>0n;)i="0123456789abcdefghijklmnopqrstuvwxyz"[Number(r%n)]+i,r/=n;return i}_parseBaseString(t,e){if(0===t.length)return this._magnitude=0n,void this._finishInitialization();this._magnitude=0n;const i=BigInt(e);let n=r.groupSizes[e],s=BigInt(r.groupBases[e]);0!==n&&0n!==s||(n=Math.floor(Math.log(67108863)/Math.log(e)),0===n&&(n=1),s=i**BigInt(n));let a=0;const o=t.length;let c=o%n;if(0===c&&o>0&&(c=n),c>0){const i=t.substring(a,a+c);this._magnitude=BigInt(this._parseBaseWord(i,e)),a+=c}for(;a<o;){const i=t.substring(a,a+n),r=BigInt(this._parseBaseWord(i,e));this._magnitude=this._magnitude*s+r,a+=n}this._finishInitialization()}_parseBaseWord(t,e){let i=0;for(let r=0;r<t.length;r++){const n=t.charCodeAt(r);let s;if(n>=48&&n<=57)s=n-48;else if(n>=65&&n<=90)s=n-65+10;else{if(!(n>=97&&n<=122))throw new Error("Invalid character: "+t[r]);s=n-97+10}if(s>=e)throw new Error("Invalid character");i=i*e+s}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/r.wordSize))}}assert(t,e="Assertion failed"){if(!t)throw new Error(e)}initNumber(t,e="be"){if(this.assert(BigInt(Math.abs(t))<=r.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 r(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=r.groupSizes[t],n=BigInt(r.groupBases[t]);0!==i&&0n!==n||(i=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(t)),0===i&&(i=1),n=BigInt(t)**BigInt(i));let s="",a=this._magnitude;for(;a>0n;){const e=a%n;a/=n;const o=this._bigIntToStringInBase(e,t);if(a>0n){const t=i-o.length;s=t>0&&t<r.zeros.length?r.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>r.MAX_SAFE_INTEGER_BIGINT||t<r.MIN_SAFE_INTEGER_BIGINT)throw new Error("Number can only safely store up to 53 bits");return Number(t)}toJSON(){const t=this._getMinimalHex();return(this.isNeg()?"-":"")+t}toArrayLikeGeneric(t,e){let i=this._magnitude,r=e?0:t.length-1;const n=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+=n}}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 n=new Array(r).fill(0);return 0n===this._magnitude&&r>0?n:0n===this._magnitude&&0===r?[]:(this.toArrayLikeGeneric(n,"le"===t),n)}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 r.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 n=new r(0n);return n._initializeState(i,0),n}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),n=new r(0n);return n._setValueFromSigned(t),n}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 n=this._nominalWordLength;return r&&(n=Math.max(this.length,t.length)),this._magnitude=i,this._finishInitialization(),r&&(this._nominalWordLength=Math.max(this._nominalWordLength,n)),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/r.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 n=Math.floor(t/r.wordSize)+1;return this._nominalWordLength=Math.max(this._nominalWordLength,n),this._finishInitialization(),this.strip()}iadd(t){return this._setValueFromSigned(this._getSignedValue()+t._getSignedValue()),this}add(t){const e=new r(0n);return e._setValueFromSigned(this._getSignedValue()+t._getSignedValue()),e}isub(t){return this._setValueFromSigned(this._getSignedValue()-t._getSignedValue()),this}sub(t){const e=new r(0n);return e._setValueFromSigned(this._getSignedValue()-t._getSignedValue()),e}mul(t){const e=new r(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)<=r.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()*BigInt(t)),this}muln(t){return this.clone().imuln(t)}sqr(){const t=new r(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 r(1n);const e=new r(1n),i=this.clone(),n=t.clone(),s=i.isNeg(),a=n.isOdd();for(s&&i.ineg();!n.isZero();)n.isOdd()&&e.imul(i),i.isqr(),n.iushrn(1);return s&&a&&e.ineg(),e}iushln(t){return this.assert("number"==typeof t&&t>=0),0===t?this:(this._magnitude<<=BigInt(t),this._finishInitialization(),this.strip())}ishln(t){return this.assert(0===this._sign,"ishln requires positive number"),this.iushln(t)}iushrn(t,e,i){if(this.assert("number"==typeof t&&t>=0),0===t)return null!=i&&i._initializeState(0n,0),this;if(null!=i){const e=(1n<<BigInt(t))-1n,r=this._magnitude&e;i._initializeState(r,0)}return this._magnitude>>=BigInt(t),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 n=0===t?1:Math.max(1,Math.ceil(t/r.wordSize));return this._nominalWordLength=n,this._finishInitialization(),this._nominalWordLength=Math.max(this._nominalWordLength,n),this.strip()}maskn(t){return this.clone().imaskn(t)}iaddn(t){return this.assert("number"==typeof t),this.assert(Math.abs(t)<=r.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)<=r.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 r(0n);return{div:"mod"!==e?t:null,mod:"div"!==e?t:null}}const n=this._getSignedValue(),s=t._getSignedValue();let a=null,o=null;"mod"!==e&&(a=n/s),"div"!==e&&(o=n%s,!0===i&&o<0n&&(o+=s<0n?-s:s));const c=null!==a?new r(0n):null;null!==c&&null!==a&&c._setValueFromSigned(a);const h=null!==o?new r(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 n=e/i;const s=e%i;if(0n===s){const t=new r(0n);return t._setValueFromSigned(n),t}2n*(s<0n?-s:s)>=(i<0n?-i:i)&&(e>0n&&i>0n||e<0n&&i<0n?n+=1n:n-=1n);const a=new r(0n);return a._setValueFromSigned(n),a}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)<=r.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,n=1n,s=0n,a=0n,o=1n;for(;0n!==i;){const t=e/i;let r=i;i=e%i,e=r,r=s,s=n-t*s,n=r,r=o,o=a-t*o,a=r}const c=new r(0n);c._setValueFromSigned(n);const h=new r(0n);h._setValueFromSigned(a);const d=new r(0n);return d._initializeState(e<0n?-e:e,0),{a:c,b:h,gcd:d}}gcd(t){let e=this._magnitude,i=t._magnitude;if(0n===e){const t=new r(0n);return t._setValueFromSigned(i),t.iabs()}if(0n===i){const t=new r(0n);return t._setValueFromSigned(e),t.iabs()}for(;0n!==i;){const t=e%i;e=i,i=t}const n=new r(0n);return n._initializeState(e,0),n}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)<=r.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 r(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 r(t,16)}static fromNumber(t){return new r(t)}static fromString(t,e){return new r(t,e)}static fromSm(t,e="big"){if(0===t.length)return new r(0n);let i=0,n="";if("little"===e){const e=t.length-1;let r=t[e];128&r&&(i=1,r&=127),n+=(r<16?"0":"")+r.toString(16);for(let i=e-1;i>=0;i--){const e=t[i];n+=(e<16?"0":"")+e.toString(16)}}else{let e=t[0];128&e&&(i=1,e&=127),n+=(e<16?"0":"")+e.toString(16);for(let e=1;e<t.length;e++){const i=t[e];n+=(i<16?"0":"")+i.toString(16)}}const s=""===n?0n:BigInt("0x"+n),a=new r(0n);return a._initializeState(s,i),a}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)r[i++]=parseInt(e.slice(t,t+2),16);return 1===this._sign?128&r[0]?r.unshift(128):r[0]|=128:128&r[0]&&r.unshift(0),"little"===t?r.reverse():r}static fromBits(t,e=!1){const i=t>>>24,n=8388607&t,s=!!(8388608&t);if(e&&s)throw new Error("negative bit set");if(0===i&&0===n){if(s&&e)throw new Error("negative bit set for zero value");return new r(0n)}const a=new r(n);return i<=3?a.iushrn(8*(3-i)):a.iushln(8*(i-3)),s&&a.ineg(),a}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 n,s=i.length;if(0!==s||e.isZero()||(i=[0],s=1),e.isZero()&&(s=0,i=[]),0===s)n=0;else if(s<=3){n=0;for(let t=0;t<s;t++)n=n<<8|i[t]}else n=i[0]<<16|i[1]<<8|i[2];8388608&n&&s<=255&&(n>>>=8,s++);let a=s<<24|n;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 r(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 r.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");let e=this.umod(t)._magnitude,i=t._magnitude,n=1n,s=0n;const a=t._magnitude;for(;e>1n&&i>1n;){let t=0;for(;0n===(e>>BigInt(t)&1n);)t++;if(t>0){e>>=BigInt(t);for(let e=0;e<t;++e)0n!==(1n&n)&&(n+=a),n>>=1n}let r=0;for(;0n===(i>>BigInt(r)&1n);)r++;if(r>0){i>>=BigInt(r);for(let t=0;t<r;++t)0n!==(1n&s)&&(s+=a),s>>=1n}e>=i?(e-=i,n-=s):(i-=e,s-=n)}let o;if(1n===e)o=n;else if(1n===i)o=s;else if(0n===e&&1n===i)o=s;else{if(0n!==i||1n!==e)throw new Error("_invmp: GCD is not 1, inverse does not exist. aVal="+e+", bVal="+i);o=n}o%=a,o<0n&&(o+=a);const c=new r(0n);return c._initializeState(o,0),c}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 n{name;p;k;n;tmp;constructor(t,e){this.name=t,this.p=new r(e,16),this.n=this.p.bitLength(),this.k=new r(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){const t=new r(BigInt(0)),e=Math.ceil(this.n/r.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 s extends n{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(t,e){const i=4194303,r=t.words,n=t.length,s=Math.min(n,9),a=new Array(s+(n>9?1:0)).fill(0);for(let t=0;t<s;t++)a[t]=r[t];let o=s;if(n<=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 d=new Array(Math.max(1,n-9)).fill(0);let u=0;for(let t=10;t<n;t++){const e=0|r[t];u<d.length&&(d[u++]=(e&i)<<4|c>>>22),c=e}c>>>=22,u<d.length?d[u++]=c:0!==c&&d.length;const l=new Array(u);for(let t=0;t<u;++t)l[t]=d[t];t.words=l}imulK(t){const e=t.words,i=t.length,r=i+2,n=new Array(r).fill(0);for(let t=0;t<i;t++)n[t]=e[t];let s=0;for(let t=0;t<r;t++){const e=0|n[t];s+=977*e,n[t]=67108863&s,s=64*e+(s/67108864|0)}return t.words=n,t}}class a{prime;m;constructor(t){if("k256"===t){const t=new s;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(!(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):(r.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.add(e);return i.cmp(this.m)>=0&&i.isub(this.m),i.forceRed(this)}iadd(t,e){this.verify2(t,e);const i=t.iadd(e);return i.cmp(this.m)>=0&&i.isub(this.m),i}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 r(1)).iushrn(2);return this.pow(t,e)}const i=this.m.subn(1);let n=0;for(;!i.isZero()&&0===i.andln(1);)n++,i.iushrn(1);this.assert(!i.isZero());const s=new r(1).toRed(this),a=s.redNeg(),o=this.m.subn(1).iushrn(1),c=this.m.bitLength(),h=new r(2*c*c).toRed(this);for(;0!==this.pow(h,o).cmp(a);)h.redIAdd(a);let d=this.pow(h,i),u=this.pow(t,i.addn(1).iushrn(1)),l=this.pow(t,i),f=n;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(d,new r(1).iushln(f-e-1));u=u.redMul(i),d=i.redSqr(),l=l.redMul(d),f=e}return u}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(e.isZero())return new r(1).toRed(this);if(0===e.cmpn(1))return t.clone();const i=new Array(16);i[0]=new r(1).toRed(this),i[1]=t;let n=2;for(;n<i.length;n++)i[n]=this.mul(i[n-1],t);let s=i[0],a=0,o=0,c=e.bitLength()%26;for(0===c&&(c=26),n=e.length-1;n>=0;n--){const t=e.words[n];for(let e=c-1;e>=0;e--){const r=t>>e&1;s!==i[0]&&(s=this.sqr(s)),0!==r||0!==a?(a<<=1,a|=r,o++,(4===o||0===n&&0===e)&&(s=this.mul(s,i[a]),o=0,a=0)):o=0}c=26}return s}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 o extends a{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 r(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),n=i.isub(r).iushrn(this.shift);let s=n;return n.cmp(this.m)>=0?s=n.isub(this.m):n.cmpn(0)<0&&(s=n.iadd(this.m)),s.forceRed(this)}mul(t,e){if(t.isZero()||e.isZero())return new r(0).forceRed(this);const i=t.mul(e),n=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),s=i.isub(n).iushrn(this.shift);let a=s;return s.cmp(this.m)>=0?a=s.isub(this.m):s.cmpn(0)<0&&(a=s.iadd(this.m)),a.forceRed(this)}invm(t){return this.imod(t._invmp(this.m).mul(this.r2)).forceRed(this)}}class c{curve;type;precomputed;constructor(t){this.curve=new ht,this.type=t,this.precomputed=null}}class h extends c{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 r(0)):(r.isBN(t)||(t=new r(t,16)),this.x=t,r.isBN(e)||(e=new r(e,16)),this.y=e,r.isBN(i)||(i=new r(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}toP(){if(this.isInfinity())return new ot(null,null);const t=this.z.redInvm(),e=t.redSqr(),i=this.x.redMul(e),r=this.y.redMul(e).redMul(t);return new ot(i,r)}neg(){return new h(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),n=t.x.redMul(i),s=this.y.redMul(e.redMul(t.z)),a=t.y.redMul(i.redMul(this.z)),o=r.redSub(n),c=s.redSub(a);if(0===o.cmpn(0))return 0!==c.cmpn(0)?new h(null,null,null):this.dbl();const d=o.redSqr(),u=d.redMul(o),l=r.redMul(d),f=c.redSqr().redIAdd(u).redISub(l).redISub(l),p=c.redMul(l.redISub(f)).redISub(s.redMul(u)),b=this.z.redMul(t.z).redMul(o);return new h(f,p,b)}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),n=this.y,s=t.y.redMul(e).redMul(this.z),a=i.redSub(r),o=n.redSub(s);if(0===a.cmpn(0))return 0!==o.cmpn(0)?new h(null,null,null):this.dbl();const c=a.redSqr(),d=c.redMul(a),u=i.redMul(c),l=o.redSqr().redIAdd(d).redISub(u).redISub(u),f=o.redMul(u.redISub(l)).redISub(n.redMul(d)),p=this.z.redMul(a);return new h(l,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(),n=this.y.redSqr(),s=n.redSqr();let a=this.x.redAdd(n).redSqr().redISub(r).redISub(s);a=a.redIAdd(a);const o=r.redAdd(r).redIAdd(r),c=o.redSqr().redISub(a).redISub(a);let h=s.redIAdd(s);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(),n=this.y.redSqr(),s=n.redSqr();let a=this.x.redAdd(n).redSqr().redISub(r).redISub(s);a=a.redIAdd(a);const o=r.redAdd(r).redIAdd(r),c=o.redSqr();let h=s.redIAdd(s);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 h(t,e,i)}eq(t){if("affine"===t.type)return this.eq(t.toJ());if(this===t)return!0;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),n=i.redMul(t.z);return 0===this.y.redMul(n).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 n=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(n),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 d=(t,e="Hash assertion failed")=>{if(!t)throw new Error(e)};class u{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=f(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 n=i-0;d(n%4==0);const s=new Array(n/4);for(let e=0,i=0;e<s.length;e++,i+=4){let n;n="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],s[e]=n>>>0}return s}(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()),d(null===this.pending),this._digest()}digestHex(){return this.update(this._pad()),d(null===this.pending),this._digestHex()}_pad(){let t=this.pendingTotal;const e=this._delta8,i=e-(t+this.padLength)%e,r=new Array(i+this.padLength);let n,s;for(r[0]=128,n=1;n<i;n++)r[n]=0;if(t<<=3,"big"===this.endian){for(s=8;s<this.padLength;s++)r[n++]=0;r[n++]=0,r[n++]=0,r[n++]=0,r[n++]=0,r[n++]=t>>>24&255,r[n++]=t>>>16&255,r[n++]=t>>>8&255,r[n++]=255&t}else for(r[n++]=255&t,r[n++]=t>>>8&255,r[n++]=t>>>16&255,r[n++]=t>>>24&255,r[n++]=0,r[n++]=0,r[n++]=0,r[n++]=0,s=8;s<this.padLength;s++)r[n++]=0;return r}}function l(t,e){return 55296==(64512&t.charCodeAt(e))&&!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1))}function f(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 n=t.charCodeAt(r);n<128?i[e++]=n:n<2048?(i[e++]=n>>6|192,i[e++]=63&n|128):l(t,r)?(n=65536+((1023&n)<<10)+(1023&t.charCodeAt(++r)),i[e++]=n>>18|240,i[e++]=n>>12&63|128,i[e++]=n>>6&63|128,i[e++]=63&n|128):(i[e++]=n>>12|224,i[e++]=n>>6&63|128,i[e++]=63&n|128)}}else{(t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+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 p(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function b(t,e){let i="";for(let n=0;n<t.length;n++){let s=t[n];"little"===e&&(s=p(s)),i+=7===(r=s.toString(16)).length?"0"+r:6===r.length?"00"+r:5===r.length?"000"+r:4===r.length?"0000"+r:3===r.length?"00000"+r:2===r.length?"000000"+r:1===r.length?"0000000"+r:r}var r;return i}function g(t,e){const i=new Array(4*t.length);for(let r=0,n=0;r<t.length;r++,n+=4){const s=t[r];"big"===e?(i[n]=s>>>24,i[n+1]=s>>>16&255,i[n+2]=s>>>8&255,i[n+3]=255&s):(i[n+3]=s>>>24,i[n+2]=s>>>16&255,i[n+1]=s>>>8&255,i[n]=255&s)}return i}function y(t,e){return t>>>e|t<<32-e}function m(t,e){return t<<e|t>>>32-e}function w(t,e){return t+e>>>0}function I(t,e,i){return t+e+i>>>0}function v(t,e,i,r){return t+e+i+r>>>0}function k(t,e,i,r,n){return t+e+i+r+n>>>0}function S(t,e,i,r){return 0===t?_(e,i,r):1===t||3===t?function(t,e,i){return t^e^i}(e,i,r):2===t?E(e,i,r):void 0}function _(t,e,i){return t&e^~t&i}function E(t,e,i){return t&e^t&i^e&i}function P(t){return y(t,2)^y(t,13)^y(t,22)}function O(t){return y(t,6)^y(t,11)^y(t,25)}function N(t){return y(t,7)^y(t,18)^t>>>3}const A=[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],x=[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],T=[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],C=[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 F(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 R(t){return t<=15?0:t<=31?1518500249:t<=47?1859775393:t<=63?2400959708:2840853838}function B(t){return t<=15?1352829926:t<=31?1548603684:t<=47?1836072691:t<=63?2053994217:0}class L extends u{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],n=this.h[1],s=this.h[2],a=this.h[3],o=this.h[4],c=r,h=n,d=s,u=a,l=o;for(let f=0;f<80;f++)i=w(m(v(r,F(f,n,s,a),t[A[f]+e],R(f)),T[f]),o),r=o,o=a,a=m(s,10),s=n,n=i,i=w(m(v(c,F(79-f,h,d,u),t[x[f]+e],B(f)),C[f]),l),c=l,l=u,u=m(d,10),d=h,h=i;i=I(this.h[1],s,u),this.h[1]=I(this.h[2],a,l),this.h[2]=I(this.h[3],o,c),this.h[3]=I(this.h[4],r,h),this.h[4]=I(this.h[0],n,d),this.h[0]=i}_digest(){return g(this.h,"little")}_digestHex(){return b(this.h,"little")}}class D extends u{h;W;k;constructor(){super(512,256,192,64),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=[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],this.W=new Array(64)}_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]=v(y(n=i[r-2],17)^y(n,19)^n>>>10,i[r-7],N(i[r-15]),i[r-16]);var n;let s=this.h[0],a=this.h[1],o=this.h[2],c=this.h[3],h=this.h[4],u=this.h[5],l=this.h[6],f=this.h[7];for(d(this.k.length===i.length),r=0;r<i.length;r++){const t=k(f,O(h),_(h,u,l),this.k[r],i[r]),e=w(P(s),E(s,a,o));f=l,l=u,u=h,h=w(c,t),c=o,o=a,a=s,s=w(t,e)}this.h[0]=w(this.h[0],s),this.h[1]=w(this.h[1],a),this.h[2]=w(this.h[2],o),this.h[3]=w(this.h[3],c),this.h[4]=w(this.h[4],h),this.h[5]=w(this.h[5],u),this.h[6]=w(this.h[6],l),this.h[7]=w(this.h[7],f)}_digest(){return g(this.h,"big")}_digestHex(){return b(this.h,"big")}}class M extends u{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]=m(i[r-3]^i[r-8]^i[r-14]^i[r-16],1);let n=this.h[0],s=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=k(m(n,5),S(t,s,a,o),c,i[r],this.k[t]);c=o,o=a,a=m(s,30),s=n,n=e}this.h[0]=w(this.h[0],n),this.h[1]=w(this.h[1],s),this.h[2]=w(this.h[2],a),this.h[3]=w(this.h[3],o),this.h[4]=w(this.h[4],c)}_digest(){return g(this.h,"big")}_digestHex(){return b(this.h,"big")}}class V{inner;outer;blockSize=64;outSize=32;constructor(t){let e;for((t=f(t,"hex")).length>this.blockSize&&(t=(new D).update(t).digest()),d(t.length<=this.blockSize),e=t.length;e<this.blockSize;e++)t.push(0);for(e=0;e<t.length;e++)t[e]^=54;for(this.inner=(new D).update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=(new D).update(t)}update(t,e){return this.inner.update(t,e),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}const q=(t,e)=>(new D).update(t,e).digest(),H=(t,e)=>{const i=(new D).update(t,e).digest();return(new D).update(i).digest()},K=(t,e)=>{const i=(new D).update(t,e).digest();return(new L).update(i).digest()},U=(t,e,i)=>new V(t).update(e,i).digest(),$=t=>{let e="";for(const r of t)e+=(i=r.toString(16)).length%2==1?"0"+i:i;var i;return e},W=(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 z(t);case"base64":return j(t);default:return function(t){const e=[];for(let i=0;i<t.length;i++){const r=t.codePointAt(i);if(void 0===r)throw new Error(`Index out of range: ${i}`);let n=r;n>65535?i++:n>=55296&&n<=57343&&(n=65533),n<=127?e.push(n):n<=2047?e.push(192|n>>6,128|63&n):n<=65535?e.push(224|n>>12,128|n>>6&63,128|63&n):e.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}return e}(t)}},z=t=>{(t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t);const e=[];for(let i=0;i<t.length;i+=2)e.push(parseInt(t[i]+t[i+1],16));return e},j=t=>{const e=[];let i=0,r=0;for(const n of t.replace(/=+$/,""))i=i<<6|"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(n),r+=6,r>=8&&(r-=8,e.push(i>>r&255),i&=(1<<r)-1);return e},X=t=>{let e="",i=0;for(let r=0;r<t.length;r++){const n=t[r];if(i>0)i--;else if(n<=127)e+=String.fromCharCode(n);else if(n>=192&&n<=223){i=1;const s=(31&n)<<6|63&t[r+1];e+=String.fromCharCode(s)}else if(n>=224&&n<=239){i=2;const s=(15&n)<<12|(63&t[r+1])<<6|63&t[r+2];e+=String.fromCharCode(s)}else if(n>=240&&n<=247){i=3;const s=(7&n)<<18|(63&t[r+1])<<12|(63&t[r+2])<<6|63&t[r+3],a=55296+(s-65536>>10),o=56320+(s-65536&1023);e+=String.fromCharCode(a,o)}}return e},G=(t,e)=>{switch(e){case"hex":return $(t);case"utf8":return X(t);default:return t}};function Y(t){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let i,r="";for(i=0;i<t.length;i+=3){const n=t[i],s=i+1<t.length?t[i+1]:0,a=i+2<t.length?t[i+2]:0,o=(3&n)<<4|s>>4,c=(15&s)<<2|a>>6,h=63&a;r+=e.charAt(n>>2)+e.charAt(o),r+=i+1<t.length?e.charAt(c):"=",r+=i+2<t.length?e.charAt(h):"="}return r}const J="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Z=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,n=(t.length-r)*(Math.log(58)/Math.log(256))+1>>>0,s=new Uint8Array([...new Uint8Array(r),...(t.match(/./gmu)??[]).map((t=>J.indexOf(t))).reduce(((t,e)=>t.map((t=>{const i=58*t+e;return e=i>>8,i}))),new Uint8Array(n)).reverse().filter((a=!1,t=>a=a||t))]);var a;return[...s]},Q=t=>{const e=Array(256).fill(-1);for(let t=0;t<58;++t)e[J.charCodeAt(t)]=t;const i=[];for(const r of t){let t=r;for(let r=0;r<i.length;++r){const n=(e[i[r]]<<8)+t;i[r]=J.charCodeAt(n%58),t=n/58|0}for(;0!==t;)i.push(J.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)},tt=(t,e=[0])=>{let i=H([...e,...t]);return i=[...e,...t,...i.slice(0,4)],Q(i)},et=(t,e,i=1)=>{const r=Z(t);let n=r.slice(0,i),s=r.slice(i,-4),a=[...n,...s];return a=H(a),r.slice(-4).forEach(((t,e)=>{if(t!==a[e])throw new Error("Invalid checksum")})),"hex"===e&&(n=$(n),s=$(s)),{prefix:n,data:s}};class it{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}toArray(){const t=this.length,e=new Array(t);let i=0;for(const t of this.bufs)for(const r of t)e[i++]=r;return e}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.bufs.push(e),this.length+=e.length,this}writeUInt8(t){const e=new Array(1);return e[0]=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.bufs.push(e),this.length+=2,this}writeInt16BE(t){return this.writeUInt16BE(65535&t)}writeUInt16LE(t){const e=[255&t,t>>8&255];return this.bufs.push(e),this.length+=2,this}writeInt16LE(t){return this.writeUInt16LE(65535&t)}writeUInt32BE(t){const e=[t>>24&255,t>>16&255,t>>8&255,255&t];return this.bufs.push(e),this.length+=4,this}writeInt32BE(t){return this.writeUInt32BE(t>>>0)}writeUInt32LE(t){const e=[255&t,t>>8&255,t>>16&255,t>>24&255];return this.bufs.push(e),this.length+=4,this}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){const e=new r(t).toArray("be",8);return this.writeReverse(e),this}writeVarIntNum(t){const e=it.varIntNum(t);return this.write(e),this}writeVarIntBn(t){const e=it.varIntBn(t);return this.write(e),this}static varIntNum(t){let e;if(t<0)return this.varIntBn(new r(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(at)),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 r(4294967296))){const i=t.toNumber();e=[254,255&i,i>>8&255,i>>16&255,i>>24&255]}else{const i=new it;i.writeUInt8(255),i.writeUInt64LEBn(t),e=i.toArray()}return e}}class rt{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 r(t);return this.pos=this.pos+8,e}readUInt64LEBn(){const t=this.readReverse(8);return new r(t)}readInt64LEBn(){const t=this.readReverse(8);let e=new r(t);return e.gte(st)&&(e=e.sub(at)),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 r(2).pow(new r(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 r(this.readUInt16LE());case 254:return new r(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new r(t)}}}const nt=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[]},st=new r(2).pow(new r(63)),at=new r(2).pow(new r(64));class ot extends c{static red=new a("k256");static a=new r(0).toRed(ot.red);static b=new r(7).toRed(ot.red);static zero=new r(0).toRed(ot.red);x;y;inf;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");return new ot(t.slice(1,33),t.slice(33,65))}if((2===t[0]||3===t[0])&&t.length-1==32)return ot.fromX(t.slice(1,33),3===t[0]);throw new Error("Unknown point format")}static fromString(t){const e=W(t,"hex");return ot.fromDER(e)}static redSqrtOptimized(t){const e=ot.red.m.addn(1).iushrn(2);return t.redPow(e)}static fromX(t,e){if("function"==typeof BigInt){function i(t,e){return(t%e+e)%e}function n(t,e,r){let n=BigInt(1);for(t=i(t,r);e>BigInt(0);)(e&BigInt(1))===BigInt(1)&&(n=i(n*t,r)),e>>=BigInt(1),t=i(t*t,r);return n}function s(t,e){const r=n(t,e+BigInt(1)>>BigInt(2),e);return i(r*r,e)===i(t,e)?r:null}const o=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),c=BigInt(7);let h;if(t instanceof r)h=BigInt("0x"+t.toString(16));else if("string"==typeof t)h=BigInt("0x"+t);else if(Array.isArray(t))h=BigInt("0x"+$(t).padStart(64,"0"));else{if("number"!=typeof t)throw new Error("Invalid x-coordinate type");h=BigInt(t)}h=i(h,o);let d=s(i(n(h,BigInt(3),o)+c,o),o);if(null===d)throw new Error("Invalid point");const u=d%BigInt(2)===BigInt(1);(e&&!u||!e&&u)&&(d=o-d);const l=new r(h.toString(16),16),f=new r(d.toString(16),16);return new ot(l,f)}{const p=new a("k256"),b=new r(0).toRed(p),g=new r(7).toRed(p),y=new r(0).toRed(p);r.isBN(t)||(t=new r(t,16)),null==t.red&&(t=t.toRed(p));const m=t.redSqr().redMul(t).redIAdd(t.redMul(b)).redIAdd(g);let w=m.redSqrt();if(0!==w.redSqr().redSub(m).cmp(y))throw new Error("invalid point");const I=w.fromRed().isOdd();return(e&&!I||!e&&I)&&(w=w.redNeg()),new ot(t,w)}}static fromJSON(t,e){"string"==typeof t&&(t=JSON.parse(t));const i=new ot(t[0],t[1],e);if("object"!=typeof t[2])return i;const r=t=>new ot(t[0],t[1],e),n=t[2];return i.precomputed={beta:null,doubles:"object"==typeof n.doubles&&null!==n.doubles?{step:n.doubles.step,points:[i].concat(n.doubles.points.map(r))}:void 0,naf:"object"==typeof n.naf&&null!==n.naf?{wnd:n.naf.wnd,points:[i].concat(n.naf.points.map(r))}: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):(r.isBN(t)||(t=new r(t,16)),this.x=t,r.isBN(e)||(e=new r(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(){return this.curve.validate(this)}encode(t=!0,e){const i=this.curve.p.byteLength(),r=this.getX().toArray("be",i);let n;return n=t?[this.getY().isEven()?2:3].concat(r):[4].concat(r,this.getY().toArray("be",i)),"hex"!==e?n:$(n)}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 ot(new r(0),new r(0));if(0===this.x?.cmp(t.x??new r(0)))return new ot(new r(0),new r(0));let e=this.y?.redSub(t.y??new r(0))??new r(0);0!==e.cmpn(0)&&(e=e.redMul(this.x?.redSub(t.x??new r(0)).redInvm()??new r(1)));const i=e?.redSqr().redISub(this.x??new r(0)).redISub(t.x??new r(0)),n=(e??new r(1)).redMul((this.x??new r(0)).redSub(i??new r(0))).redISub(this.y??new r(0));return new ot(i??new r(0),n??new r(0))}dbl(){if(this.inf)return this;const t=(this.y??new r(0)).redAdd(this.y??new r(0));if(0===t.cmpn(0))return new ot(new r(0),new r(0));const e=this.curve.a,i=(this.x??new r(0)).redSqr(),n=t.redInvm(),s=i.redAdd(i).redIAdd(i).redIAdd(e).redMul(n),a=s.redSqr().redISub((this.x??new r(0)).redAdd(this.x??new r(0))),o=s.redMul((this.x??new r(0)).redSub(a)).redISub(this.y??new r(0));return new ot(a,o)}getX(){return(this.x??new r(0)).fromRed()}getY(){return(this.y??new r(0)).fromRed()}mul(t){if(r.isBN(t)||(t=new r(t,16)),"function"==typeof BigInt){if(this.inf)return this;const e=BigInt(0),i=BigInt(1),n=BigInt(2),s=BigInt(3),a=BigInt(4),o=BigInt(8),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),h=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");let d=BigInt("0x"+t.toString(16));const u=d<e;if(u&&(d=-d),d=(d%h+h)%h,d===e)return new ot(null,null);if(null===this.x||null===this.y)throw new Error("Point coordinates cannot be null");const l=BigInt("0x"+this.x.fromRed().toString(16)),f=BigInt("0x"+this.y.fromRed().toString(16)),p=(t,e)=>(t%e+e)%e,b=(t,e,i)=>p(t*e,i),g=(t,e,i)=>p(t-e,i),y=(t,r)=>{let n=i,s=e,a=p(t,r),o=r;for(;a>i;){const t=o/a,e=s-n*t,i=o-a*t;s=n,n=e,o=a,a=i}return p(n,r)},m=t=>{const{X:r,Y:h,Z:d}=t;if(h===e)return{X:e,Y:i,Z:e};const u=b(h,h,c),l=b(a,b(r,u,c),c),f=b(s,b(r,r,c),c),p=g(b(f,f,c),b(n,l,c),c);return{X:p,Y:g(b(f,g(l,p,c),c),b(o,b(u,u,c),c),c),Z:b(n,b(h,d,c),c)}},w=(t,r)=>{if(t.Z===e)return r;if(r.Z===e)return t;const s=b(t.Z,t.Z,c),a=b(r.Z,r.Z,c),o=b(t.X,a,c),h=b(r.X,s,c),d=b(t.Y,b(a,r.Z,c),c),u=b(r.Y,b(s,t.Z,c),c),l=g(h,o,c),f=g(u,d,c);if(l===e)return f===e?m(t):{X:e,Y:i,Z:e};const p=b(l,l,c),y=b(l,p,c),w=b(o,p,c),I=g(g(b(f,f,c),y,c),b(n,w,c),c);return{X:I,Y:g(b(f,g(w,I,c),c),b(d,y,c),c),Z:b(l,b(t.Z,r.Z,c),c)}},I=((t,r)=>{let n={X:r.x,Y:r.y,Z:i},s={X:e,Y:i,Z:e},a=t;for(;a>e;)(a&i)===i&&(s=w(s,n)),n=m(n),a>>=i;return s})(d,{x:l,y:f});if(I.Z===e)return new ot(null,null);const v=y(I.Z,c),k=b(v,v,c),S=b(I.X,k,c),_=b(I.Y,b(k,v,c),c),E=new r(S.toString(16),16),P=new r(_.toString(16),16),O=new ot(E,P);return u?O.neg():O}return this.isInfinity()?this:this._hasDoubles(t)?this._fixedNafMul(t):this._endoWnafMulAdd([this],[t])}mulAdd(t,e,i){const r=[this,e],n=[t,i];return this._endoWnafMulAdd(r,n)}jmulAdd(t,e,i){const r=[this,e],n=[t,i];return this._endoWnafMulAdd(r,n,!0)}eq(t){return this===t||this.inf===t.inf&&(this.inf||0===(this.x??new r(0)).cmp(t.x??new r(0))&&0===(this.y??new r(0)).cmp(t.y??new r(0)))}neg(t){if(this.inf)return this;const e=new ot(this.x,(this.y??new r(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 h(null,null,null):new h(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 ot((this.x??new r(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 ot(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 n=[];for(let t=0;t<i.length;t+=e.step){let r=0;for(let n=t+e.step-1;n>=t;n--)r=(r<<1)+i[n];n.push(r)}let s=new h(null,null,null),a=new h(null,null,null);for(let t=r;t>0;t--){for(let i=0;i<n.length;i++){const r=n[i];r===t?a=a.mixedAdd(e.points[i]):r===-t&&(a=a.mixedAdd(e.points[i].neg()))}s=s.add(a)}return s.toP()}_wnafMulAdd(t,e,i,n,s){const a=this.curve._wnafT1.map((t=>t.toNumber())),o=this.curve._wnafT2.map((()=>[])),c=this.curve._wnafT3.map((()=>[]));let d=0;for(let i=0;i<n;i++){const r=e[i]._getNAFPoints(t);a[i]=r.wnd,o[i]=r.points}for(let t=n-1;t>=1;t-=2){const n=t-1,s=t;if(1!==a[n]||1!==a[s]){c[n]=this.curve.getNAF(i[n],a[n],this.curve._bitLength),c[s]=this.curve.getNAF(i[s],a[s],this.curve._bitLength),d=Math.max(c[n].length,d),d=Math.max(c[s].length,d);continue}const h=[e[n],null,null,e[s]];0===(e[n].y??new r(0)).cmp(e[s].y??new r(0))?(h[1]=e[n].add(e[s]),h[2]=e[n].toJ().mixedAdd(e[s].neg())):0===(e[n].y??new r(0)).cmp((e[s].y??new r(0)).redNeg())?(h[1]=e[n].toJ().mixedAdd(e[s]),h[2]=e[n].add(e[s].neg())):(h[1]=e[n].toJ().mixedAdd(e[s]),h[2]=e[n].toJ().mixedAdd(e[s].neg()));const u=[-3,-1,-5,-7,0,7,5,1,3],l=this.curve.getJSF(i[n],i[s]);d=Math.max(l[0].length,d),c[n]=new Array(d),c[s]=new Array(d);for(let t=0;t<d;t++){const e=0|l[0][t],i=0|l[1][t];c[n][t]=u[3*(e+1)+(i+1)],c[s][t]=0,o[n]=h}}let u=new h(null,null,null);const l=this.curve._wnafT4;for(let t=d;t>=0;t--){let e=0;for(;t>=0;){let i=!0;for(let e=0;e<n;e++)l[e]=new r("number"==typeof c[e][t]?c[e][t]:0),l[e].isZero()||(i=!1);if(!i)break;e++,t--}if(t>=0&&e++,u=u.dblp(e),t<0)break;const i=new r(1),s=new r(2);for(let t=0;t<n;t++){const e=l[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<n;t++)o[t]=[];return!0===s?u:u.toP()}_endoWnafMulAdd(t,e,i){const n=new Array(2*t.length),s=new Array(2*t.length);let a;for(a=0;a<t.length;a++){const i=this.curve._endoSplit(e[a]);let o=t[a],c=o._getBeta()??new ot(new r(0),new r(0));0!==i.k1.negative&&(i.k1.ineg(),o=o.neg(!0)),0!==i.k2.negative&&(i.k2.ineg(),c=c.neg(!0)),n[2*a]=o,n[2*a+1]=c,s[2*a]=i.k1,s[2*a+1]=i.k2}const o=this._wnafMulAdd(1,n,s,2*a,i);for(let t=0;t<2*a;t++)n[t]=null,s[t]=null;return o}_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 n=0;n<(e??0);n+=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 ct;class ht{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 n=1<<e+1,s=t.clone();for(let t=0;t<r.length;t++){let e;const i=s.andln(n-1);s.isOdd()?(e=i>(n>>1)-1?(n>>1)-i:i,s.isubn(e)):e=0,r[t]=e,s.iushrn(1)}return r}getJSF(t,e){const i=[[],[]];t=t.clone(),e=e.clone();let r=0,n=0;for(;t.cmpn(-r)>0||e.cmpn(-n)>0;){let s,a,o=t.andln(3)+r&3,c=e.andln(3)+n&3;if(3===o&&(o=-1),3===c&&(c=-1),1&o){const e=t.andln(7)+r&7;s=3!==e&&5!==e||2!==c?o:-o}else s=0;if(i[0].push(s),1&c){const t=e.andln(7)+n&7;a=3!==t&&5!==t||2!==o?c:-c}else a=0;i[1].push(a),2*r===s+1&&(r=1-r),2*n===a+1&&(n=1-n),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?W(t,"hex"):t}static intFromLE(t){return new r(t,"hex","le")}constructor(){if(void 0!==ct)return ct;ct=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 r(t.p,16),this.red=new a(t.prime),this.zero=new r(0).toRed(this.red),this.one=new r(1).toRed(this.red),this.two=new r(2).toRed(this.red),this.n=new r(t.n,16),this.g=ot.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 r(t.a,16).toRed(this.red),this.b=new r(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,n;if(void 0!==t.beta)e=new r(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 r(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,n=null!=this.g.x?this.g.x.redMul(e):void 0;if(null!=r&&null!=n&&0===r.cmp(n))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,n=null!=this.g.x?this.g.x.redMul(e):void 0;if(null==r||null==n)throw new Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");ht.assert(0===r.cmp(n),"Lambda selection does not match computed beta.")}}return n="object"==typeof t.basis&&null!==t.basis?t.basis.map((function(t){return{a:new r(t.a,16),b:new r(t.b,16)}})):this._getEndoBasis(i),{beta:e,lambda:i,basis:n}}_getEndoRoots(t){const e=t===this.p?this.red:new o(t),i=new r(2).toRed(e).redInvm(),n=i.redNeg(),s=new r(3).toRed(e).redNeg().redSqrt().redMul(i);return[n.redAdd(s).fromRed(),n.redSub(s).fromRed()]}_getEndoBasis(t){const e=this.n.ushrn(Math.floor(this.n.bitLength()/2));let i,n,s,a,o,c,h=t,d=this.n.clone(),u=new r(1),l=new r(0),f=new r(0),p=new r(1),b=new r(0),g=0,y=new r(0),m=new r(0);for(;0!==h.cmpn(0);){const t=d.div(h);y=d.sub(t.mul(h)),m=f.sub(t.mul(u));const r=p.sub(t.mul(l));if(void 0===s&&y.cmp(e)<0)i=b.neg(),n=u,s=y.neg(),a=m;else if(void 0!==s&&2==++g)break;b=y,d=h,h=y,f=u,u=m,p=l,l=r}if(void 0===i||void 0===n||void 0===s||void 0===a)throw new Error("Failed to compute Endo Basis values");o=y.neg(),c=m;const w=s.sqr().add(a.sqr());return o.sqr().add(c.sqr()).cmp(w)>=0&&(o=i,c=n),0!==s.negative&&(s=s.neg(),a=a.neg()),0!==o.negative&&(o=o.neg(),c=c.neg()),[{a:s,b:a},{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],n=r.b.mul(t).divRound(this.n),s=i.b.neg().mul(t).divRound(this.n),a=n.mul(i.a),o=s.mul(r.a),c=n.mul(i.b),h=s.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),n=e.redSqr().redMul(e).redIAdd(r).redIAdd(this.b);return 0===i.redSqr().redISub(n).cmpn(0)}}class dt{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=W(t,e);const n=new class{place;constructor(){this.place=0}};if(48!==t[n.place++])throw new Error("Signature DER must start with 0x30");if(i(t,n)+n.place!==t.length)throw new Error("Signature DER invalid");if(2!==t[n.place++])throw new Error("Signature DER invalid");const s=i(t,n);let a=t.slice(n.place,s+n.place);if(n.place+=s,2!==t[n.place++])throw new Error("Signature DER invalid");const o=i(t,n);if(t.length!==o+n.place)throw new Error("Invalid R-length in signature DER");let c=t.slice(n.place,o+n.place);if(0===a[0]){if(!(128&a[1]))throw new Error("Invalid R-value in signature DER");a=a.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 dt(new r(a),new r(c))}static fromCompact(t,e){if(65!==(t=W(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 dt(new r(t.slice(1,33)),new r(t.slice(33,65)))}constructor(t,e){this.r=t,this.s=e}verify(t,e,i){const n=new r(q(t,i),16);return pt(n,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(),n=this.s.toArray();for(128&r[0]&&(r=[0].concat(r)),128&n[0]&&(n=[0].concat(n)),r=i(r),n=i(n);0===n[0]&&!(128&n[1]);)n=n.slice(1);let s=[2];e(s,r.length),s=s.concat(r),s.push(2),e(s,n.length);const a=s.concat(n);let o=[48];return e(o,a.length),o=o.concat(a),"hex"===t?$(o):"base64"===t?Y(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 n=[r];return n=n.concat(this.r.toArray("be",32)),n=n.concat(this.s.toArray("be",32)),"hex"===i?$(n):"base64"===i?Y(n):n}RecoverPublicKey(t,e){const i=this.r,r=this.s,n=!!(1&t),s=t>>1,a=new ht,o=a.n,c=a.g,h=0!==s?i.add(o):i,d=ot.fromX(h,n);if(!d.mul(o).isInfinity())throw new Error("nR is not at infinity");const u=e.neg().umod(o),l=i.invm(o),f=l.mul(r).umod(o),p=l.mul(u).umod(o),b=c.mul(p).add(d.mul(f)),g=new bt(b);return g.validate(),g}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 ut{K;V;constructor(t,e){if(t=W(t,"hex"),e=W(e,"hex"),t.length<32)throw new Error("Not enough entropy. Minimum is 256 bits");const i=t.concat(e);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(i)}hmac(){return new V(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(),$(i)}}function lt(t,e,i=new ht){const r=8*t.byteLength()-i.n.bitLength();return r>0&&t.iushrn(r),null===e&&t.cmp(i.n)>=0?t.sub(i.n):t}const ft=(t,e,i=!1,n)=>{if("function"==typeof BigInt){const s=BigInt(0),a=BigInt(1),o=BigInt(2),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),h=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),d={x:BigInt("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"),y:BigInt("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")},u=BigInt("0x"+t.toString(16)),l=BigInt("0x"+e.toString(16));if(l<=s||l>=c)throw new Error("Invalid private key");function f(t,e){const i=t.toString(16).padStart(2*e,"0"),r=new Uint8Array(e);for(let t=0;t<e;t++)r[t]=parseInt(i.substr(2*t,2),16);return r}const p=32,b=f(l,p),g=f(u,p),y=new ut(Array.from(b),Array.from(g)),m=c-a;let w=0;function I(t,e,i=!0){const r=t.toString(2).length-e.toString(2).length;return r>0&&(t>>=BigInt(r)),!i&&t>=e?t-e:t}function v(t){if("function"==typeof t){const e=t(w).toString(16);return BigInt("0x"+e)}if(null!=t&&r.isBN(t)){const e=t.toString(16);return BigInt("0x"+e)}{const t=y.generate(p);return BigInt("0x"+t)}}function k(t,e){return(t%e+e)%e}function S(t,e){let i=a,r=s,n=k(t,e),o=e;for(;n>a;){const t=o/n,e=r-i*t,s=o-n*t;r=i,i=e,o=n,n=s}return k(i,e)}function _(t,e){if(null===t)return e;if(null===e)return t;if(t.x===e.x&&t.y===k(-e.y,h))return null;let i;if(t.x===e.x&&t.y===e.y){if(t.y===s)return null;const e=k(BigInt(3)*t.x*t.x,h);i=k(e*S(o*t.y,h),h)}else{const r=k(e.y-t.y,h);i=k(r*S(e.x-t.x,h),h)}const r=k(i*i-t.x-e.x,h);return{x:r,y:k(i*(t.x-r)-t.y,h)}}function E(t,e){let i=e,r=null;for(;t>BigInt(0);)t%BigInt(2)===BigInt(1)&&(r=null===r?i:_(r,i)??r),i=_(i,i)??i,t>>=BigInt(1);if(null===r)throw new Error("Scalar multiplication resulted in an invalid point.");return r}let P=!1;for(;!P;){w+=1,P=!0,w+=1;let O=v(n);if(O=I(O,c,!0),O<=a||O>=m){if(n instanceof r)throw new Error("Invalid fixed custom K value (must be more than 1 and less than N-1)");continue}const N=E(O,d);if(null===N){if(n instanceof r)throw new Error("Invalid fixed custom K value (must not create a point at infinity when multiplied by the generator point)");continue}const A=k(N.x,c);if(A===s){if(n instanceof r)throw new Error("Invalid fixed custom K value (when multiplied by G, the resulting x coordinate mod N must not be zero)");continue}const x=S(O,c),T=k(A*l,c);let C=k(x*(u+T),c);if(C===s){if(n instanceof r)throw new Error("Invalid fixed custom K value (when used with the key, it cannot create a zero value for S)");continue}i&&C>c/o&&(C=c-C);const F=new r(A.toString(16),16),R=new r(C.toString(16),16);return new dt(F,R)}}else{const B=new ht;t=lt(t);const L=B.n.byteLength(),D=e.toArray("be",L),M=t.toArray("be",L),V=new ut(D,M),q=B.n.subn(1);for(let H=0;;H++){let K="function"==typeof n?n(H):r.isBN(n)?n:new r(V.generate(L),16);if(null==K)throw new Error("k is undefined");if(K=lt(K,!0),K.cmpn(1)<=0||K.cmp(q)>=0){if(r.isBN(n))throw new Error("Invalid fixed custom K value (must be more than 1 and less than N-1)");continue}const U=B.g.mul(K);if(U.isInfinity()){if(r.isBN(n))throw new Error("Invalid fixed custom K value (must not create a point at infinity when multiplied by the generator point)");continue}const $=U.getX().umod(B.n);if(0===$.cmpn(0)){if(r.isBN(n))throw new Error("Invalid fixed custom K value (when multiplied by G, the resulting x coordinate mod N must not be zero)");continue}let W=K.invm(B.n).mul($.mul(e).iadd(t));if(W=W.umod(B.n),0!==W.cmpn(0))return i&&W.cmp(B.n.ushrn(1))>0&&(W=B.n.sub(W)),new dt($,W);if(r.isBN(n))throw new Error("Invalid fixed custom K value (when used with the key, it cannot create a zero value for S)")}}throw new Error("Failed to generate a valid signature")},pt=(t,e,i)=>{if("function"==typeof BigInt){const r=BigInt(0),n=BigInt(1),s=BigInt(2),a=BigInt(3),o=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),h={x:BigInt("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"),y:BigInt("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")},d=(t,e)=>(t%e+e)%e,u=(t,e)=>{let[i,s]=[t,e],[a,o]=[BigInt(1),BigInt(0)];for(;s!==r;){const t=i/s;[i,s]=[s,i-t*s],[a,o]=[o,a-t*o]}return i>n?r:d(a,e)},l=(t,e,i)=>d(t*e,i),f=(t,e,i)=>d(t-e,i),p=BigInt(4),b=BigInt(8),g=t=>{const{X:e,Y:i,Z:c}=t;if(i===r)return{X:r,Y:n,Z:r};const h=l(i,i,o),d=l(p,l(e,h,o),o),u=l(a,l(e,e,o),o),g=f(l(u,u,o),l(s,d,o),o);return{X:g,Y:f(l(u,f(d,g,o),o),l(b,l(h,h,o),o),o),Z:l(s,l(i,c,o),o)}},y=(t,e)=>{if(t.Z===r)return e;if(e.Z===r)return t;const i=l(t.Z,t.Z,o),a=l(e.Z,e.Z,o),c=l(t.X,a,o),h=l(e.X,i,o),d=l(t.Y,l(a,e.Z,o),o),u=l(e.Y,l(i,t.Z,o),o),p=f(h,c,o),b=f(u,d,o);if(p===r)return b===r?g(t):{X:r,Y:n,Z:r};const y=l(p,p,o),m=l(p,y,o),w=l(c,y,o),I=f(f(l(b,b,o),m,o),l(s,w,o),o);return{X:I,Y:f(l(b,f(w,I,o),o),l(d,m,o),o),Z:l(p,l(t.Z,e.Z,o),o)}},m=(t,e)=>{const i={X:e.x,Y:e.y,Z:n};let s={X:r,Y:n,Z:r};const a=t.toString(2);for(let t=0;t<a.length;t++)s=g(s),"1"===a[t]&&(s=y(s,i));return s},w=(t,e,i)=>{const{r:n,s}=i,a=t;if(n<=r||n>=c||s<=r||s>=c)return!1;const f=u(s,c);if(f===r)return!1;const p=l(a,f,c),b=l(n,f,c),g=m(p,h),w=m(b,e),I=y(g,w);if(I.Z===r)return!1;const v=u(I.Z,o);if(v===r)return!1;const k=l(v,v,o),S=l(I.X,k,o);return d(S,c)===n},I=BigInt("0x"+t.toString(16));if(null==i.x||null==i.y)throw new Error("Invalid public key: missing coordinates.");return w(I,{x:BigInt("0x"+i.x.toString(16)),y:BigInt("0x"+i.y.toString(16))},{r:BigInt("0x"+e.r.toString(16)),s:BigInt("0x"+e.s.toString(16))})}{const r=new ht;t=lt(t);const n=e.r,s=e.s;if(n.cmpn(1)<0||n.cmp(r.n)>=0)return!1;if(s.cmpn(1)<0||s.cmp(r.n)>=0)return!1;const a=s.invm(r.n),o=a.mul(t).umod(r.n),c=a.mul(n).umod(r.n),h=r.g.jmulAdd(o,i,c);return!h.isInfinity()&&h.eqXToP(n)}};class bt extends ot{static fromPrivateKey(t){const e=(new ht).g.mul(t);return new bt(e.x,e.y)}static fromString(t){const e=ot.fromString(t);return new bt(e.x,e.y)}static fromDER(t){const e=ot.fromDER(t);return new bt(e.x,e.y)}constructor(t,e=null,i=!0){if(t instanceof ot)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.mul(t)}verify(t,e,i){const n=new r(q(t,i),16);return pt(n,e,this)}toDER(t){return"hex"===t?this.encode(!0,t):this.encode(!0)}toHash(t){const e=K(this.encode(!0));return"hex"===t?$(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 tt(this.toHash(),t)}deriveChild(t,e,i,n){let s;if("function"==typeof n){const e=n(t,this);void 0!==e?s=e:(s=this.deriveSharedSecret(t),"function"==typeof i&&i(t,this,s))}else s=this.deriveSharedSecret(t);const a=W(e,"utf8"),o=U(s.encode(!0),a),c=(new ht).g.mul(new r(o)),h=this.add(c);return new bt(h.x,h.y)}static fromMsgHashAndCompactSignature(t,e,i){const n=W(e,i);if(65!==n.length)throw new Error("Invalid Compact Signature");const s=n[0];if(s<27||s>=35)throw new Error("Invalid Compact Byte");let a=n[0]-27;return a>3&&(a-=4),new dt(new r(n.slice(1,33)),new r(n.slice(33,65))).RecoverPublicKey(a,t)}}class gt{_rand;constructor(){const t=()=>{throw new Error("No secure random number generator is available in this environment.")};if(this._rand=t,"object"==typeof self)self.crypto?.getRandomValues?this._rand=t=>{const e=new Uint8Array(t);return self.crypto.getRandomValues(e),[...e]}:this._rand=t;else try{const t=require("crypto");"function"==typeof t.randomBytes&&(this._rand=e=>[...t.randomBytes(e)])}catch{this._rand=t}}generate(t){return this._rand(t)}}let yt=null;const mt=t=>(null==yt&&(yt=new gt),yt.generate(t));class wt{x;y;constructor(t,e){const i=(new ht).p;this.x=t.umod(i),this.y=e.umod(i)}toString(){return Q(this.x.toArray())+"."+Q(this.y.toArray())}static fromString(t){const[e,i]=t.split(".");return new wt(new r(Z(e)),new r(Z(i)))}}class It{points;threshold;constructor(t,e){this.points=t,this.threshold=e??t.length}static fromPrivateKey(t,e){const i=(new ht).p,n=[new wt(new r(0),new r(t.toArray()))];for(let t=1;t<e;t++){const t=new r(mt(32)).umod(i),e=new r(mt(32)).umod(i);n.push(new wt(t,e))}return new It(n)}valueAt(t){const e=(new ht).p;let i=new r(0);for(let r=0;r<this.threshold;r++){let n=this.points[r].y;for(let i=0;i<this.threshold;i++)if(r!==i){const s=this.points[i].x,a=this.points[r].x,o=t.sub(s).umod(e),c=a.sub(s).umod(e).invm(e),h=o.mul(c).umod(e);n=n.mul(h).umod(e)}i=i.add(n).umod(e)}return i}}class vt{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 n=t.split(".");if(4!==n.length)throw new Error("Invalid share format in share "+r.toString()+'. Expected format: "x.y.t.i" - received '+t);const[s,a,o,c]=n;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,wt.fromString([s,a].join("."))}));return new vt(r,e,i)}toBackupFormat(){return this.points.map((t=>t.toString()+"."+this.threshold.toString()+"."+this.integrity))}}class kt extends r{static fromRandom(){return new kt(mt(32))}static fromString(t,e="hex"){return new kt(super.fromString(t,e).toArray())}static fromHex(t){return new kt(super.fromHex(t,"big"))}static fromWif(t,e=1){const i=et(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 kt(i.data.slice(0,32))}constructor(t=0,e=10,i="be",n="apply"){if(t instanceof r?(super(),t.copy(this)):super(t,e,i),"nocheck"!==n){const t=this.checkInField();if(!t.inField){if("error"===n)throw new Error("Input is out of field");r.move(this,t.modN)}}}checkInField(){const t=new ht,e=this.mod(t.n);return{inField:0===this.cmp(e),modN:e}}isValid(){return this.checkInField().inField}sign(t,e,i=!0,n){const s=new r(q(t,e),16);return ft(s,this,i,n)}verify(t,e,i){const n=new r(q(t,i),16);return pt(n,e,this.toPublicKey())}toPublicKey(){const t=(new ht).g.mul(this);return new bt(t.x,t.y)}toWif(t=[128]){if(!this.isValid())throw new Error("Value is out of field");return tt([...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.mul(this)}deriveChild(t,e,i,n){let s;if("function"==typeof n){const e=n(this,t);void 0!==e?s=e:(s=this.deriveSharedSecret(t),"function"==typeof i&&i(this,t,s))}else s=this.deriveSharedSecret(t);const a=W(e,"utf8"),o=U(s.encode(!0),a),c=new ht;return new kt(this.add(new r(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=It.fromPrivateKey(this,t),n=[];for(let t=0;t<e;t++){const t=new r(kt.fromRandom().toArray()),e=i.valueAt(t);n.push(new wt(t,e))}const s=this.toPublicKey().toHash("hex").slice(0,8);return new vt(n,t,s)}toBackupShares(t,e){return this.toKeyShares(t,e).toBackupFormat()}static fromBackupShares(t){return kt.fromKeyShares(vt.fromBackupFormat(t))}static fromKeyShares(t){const{points:e,threshold:i,integrity:n}=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 It(e,i),a=new kt(s.valueAt(new r(0)).toArray());if(a.toPublicKey().toHash("hex").slice(0,8)!==n)throw new Error("Integrity hash mismatch");return a}}const St=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]),_t=[[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))),Et=new Uint8Array(256),Pt=new Uint8Array(256);for(let t=0;t<256;t++){const e=255&(t<<1^(128&t?27:0));Et[t]=e,Pt[t]=e^t}function Ot(t,e,i){for(let r=0;r<4;r++){const n=e[i+r];for(let e=0;e<4;e++)t[e][r]^=n[e]}}function Nt(t){for(let e=0;e<4;e++)for(let i=0;i<4;i++)t[e][i]=St[t[e][i]]}function At(t){for(let e=0;e<4;e++)t[e]=St[t[e]]}function xt(t){const e=t[0];t[0]=t[1],t[1]=t[2],t[2]=t[3],t[3]=e}function Tt(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 Ct(t){for(let e=0;e<4;e++){const i=t[0][e],r=t[1][e],n=t[2][e],s=t[3][e];t[0][e]=Et[i]^Pt[r]^n^s,t[1][e]=i^Et[r]^Pt[n]^s,t[2][e]=i^r^Et[n]^Pt[s],t[3][e]=Pt[i]^r^n^Et[s]}}function Ft(t,e){let i,r,n,s;const a=[[],[],[],[]],o=[],c=Array.from(e);if(c.length<=16){for(;c.length<16;)c.unshift(0);s=11}else if(c.length<=24){for(;c.length<24;)c.unshift(0);s=13}else{if(!(e.length<=32))throw new Error("Illegal key length: "+String(e.length));for(;c.length<32;)c.unshift(0);s=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){xt(t),At(t);const r=_t[e/i];for(let e=0;e<4;e++)t[e]^=r[e]}else i>6&&e%i==4&&At(t);for(let n=0;n<4;n++)r[e][n]=r[e-i][n]^t[n]}return r}(s,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(Ot(a,h,0),n=1;n<s;n++)Nt(a),Tt(a),n+1<s&&Ct(a),Ot(a,h,4*n);for(i=0;i<4;i++)for(r=0;r<4;r++)o.push(a[r][i]);return o}const Rt=function(t){return[(4278190080&t)>>>24,(16711680&t)>>16,(65280&t)>>8,255&t]},Bt=function(t){return new Array(t).fill(0)},Lt=[225].concat(Bt(15)),Dt=function(t,e){for(let i=0;i<t.length;i++)t[i]^=e[i]},Mt=function(t){let e,i=0,r=0;for(e=0;e<t.length;e++)r=i,i=1&t[e],t[e]=t[e]>>1,0!==r&&(t[e]=128|t[e]);return t},Vt=function(t,e){const i=e.slice(),r=Bt(16);for(let e=0;e<16;e++)for(let n=7;n>=0;n--)t[e]&1<<n&&Dt(r,i),1&i[15]?(Mt(i),Dt(i,Lt)):Mt(i);return r},qt=function(t){let e;const i=t.slice();for(e=15;11!==e&&(i[e]=i[e]+1,256===i[e]);e--)i[e]=0;return i};function Ht(t,e){let i=Bt(16);for(let r=0;r<t.length;r+=16){const n=i.slice();for(let e=0;e<16;e++)n[e]^=t[r+e]??0;i=Vt(n,e)}return i}function Kt(t,e,i){if(0===t.length)return[];const r=new Array(t.length);let n=e,s=0;const a=Math.ceil(t.length/16);for(let e=0;e<a;e++){const o=Ft(n,i),c=Math.min(16,t.length-s);for(let e=0;e<c;e++)r[s]=t[s]^o[e],s++;e+1<a&&(n=qt(n))}return r}class Ut extends r{static fromRandom(){return new Ut(mt(32))}encrypt(t,e){const i=mt(32);t=W(t,e);const{result:r,authenticationTag:n}=function(t,e,i,r){let n,s;const a=Ft(Bt(16),r);n=[...i],12===i.length?n=n.concat(Bt(3)).concat([1]):(i.length%16!=0&&(n=n.concat(Bt(16-i.length%16))),n=n.concat(Bt(8)),n=Ht(n.concat(Bt(4)).concat(Rt(8*i.length)),a));const o=Kt(t,qt(n),r);return s=e.slice(),0===e.length?s=s.concat(Bt(16)):e.length%16!=0&&(s=s.concat(Bt(16-e.length%16))),s=s.concat(o),0===o.length?s=s.concat(Bt(16)):o.length%16!=0&&(s=s.concat(Bt(16-o.length%16))),s=s.concat(Bt(4)).concat(Rt(8*e.length)).concat(Bt(4)).concat(Rt(8*o.length)),{result:o,authenticationTag:Kt(Ht(s,a),n,r)}}(t,[],i,this.toArray("be",32));return G([...i,...r,...n],e)}decrypt(t,e){const i=(t=W(t,e)).slice(0,32),r=t.slice(32),n=r.slice(-16),s=function(t,e,i,r,n){let s,a;const o=Ft(Bt(16),n);s=[...i],12===i.length?s=s.concat(Bt(3)).concat([1]):(i.length%16!=0&&(s=s.concat(Bt(16-i.length%16))),s=s.concat(Bt(8)),s=Ht(s.concat(Bt(4)).concat(Rt(8*i.length)),o));const c=Kt(t,qt(s),n);return a=e.slice(),0===e.length?a=a.concat(Bt(16)):e.length%16!=0&&(a=a.concat(Bt(16-e.length%16))),a=a.concat(t),0===t.length?a=a.concat(Bt(16)):t.length%16!=0&&(a=a.concat(Bt(16-t.length%16))),a=a.concat(Bt(4)).concat(Rt(8*e.length)).concat(Bt(4)).concat(Rt(8*t.length)),Kt(Ht(a,o),s,n).join()!==r.join()?null:c}(r.slice(0,-16),[],i,n,this.toArray());if(null===s)throw new Error("Decryption failed!");return G(s,e)}}class $t extends dt{static SIGHASH_ALL=1;static SIGHASH_NONE=2;static SIGHASH_SINGLE=3;static SIGHASH_FORKID=64;static SIGHASH_ANYONECANPAY=128;scope;static format(t){const e={sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,sequence:t.inputSequence},i=[...t.otherInputs];function r(e){const i=new it;if(void 0===e)for(const e of t.outputs){const t=e.satoshis??0;i.writeUInt64LE(t);const r=e.lockingScript?.toBinary()??[];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 n=r.satoshis??0;i.writeUInt64LE(n);const s=r.lockingScript?.toBinary()??[];i.writeVarIntNum(s.length),i.write(s)}const r=i.toArray();return H(r)}i.splice(t.inputIndex,0,e);let n=new Array(32).fill(0),s=new Array(32).fill(0),a=new Array(32).fill(0);t.scope&$t.SIGHASH_ANYONECANPAY||(n=(()=>{const t=new it;for(const e of i){if(void 0===e.sourceTXID){if(null==e.sourceTransaction)throw new Error("Missing sourceTransaction for input");t.write(e.sourceTransaction.hash())}else t.writeReverse(W(e.sourceTXID,"hex"));t.writeUInt32LE(e.sourceOutputIndex)}const e=t.toArray();return H(e)})()),t.scope&$t.SIGHASH_ANYONECANPAY||(31&t.scope)===$t.SIGHASH_SINGLE||(31&t.scope)===$t.SIGHASH_NONE||(s=(()=>{const t=new it;for(const e of i){const i=e.sequence??4294967295;t.writeUInt32LE(i)}const e=t.toArray();return H(e)})()),(31&t.scope)!==$t.SIGHASH_SINGLE&&(31&t.scope)!==$t.SIGHASH_NONE?a=r():(31&t.scope)===$t.SIGHASH_SINGLE&&t.inputIndex<t.outputs.length&&(a=r(t.inputIndex));const o=new it;o.writeInt32LE(t.transactionVersion),o.write(n),o.write(s),o.writeReverse(W(t.sourceTXID,"hex")),o.writeUInt32LE(t.sourceOutputIndex);const c=t.subscript.toBinary();o.writeVarIntNum(c.length),o.write(c),o.writeUInt64LE(t.sourceSatoshis);const h=e.sequence;return o.writeUInt32LE(h),o.write(a),o.writeUInt32LE(t.lockTime),o.writeUInt32LE(t.scope>>>0),o.toArray()}static fromChecksigFormat(t){if(0===t.length){const t=new r(1),e=new r(1);return new $t(t,e,1)}const e=t[t.length-1],i=t.slice(0,t.length-1),n=dt.fromDER(i);return new $t(n.r,n.s,e)}constructor(t,e,i){super(t,e),this.scope=i}hasLowS(){return!this.s.ltn(1)&&!this.s.gt(new r("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex"))}toChecksigFormat(){return[...this.toDER(),this.scope]}}class Wt{curve;constructor(){this.curve=new ht}generateProof(t,e,i,r){const n=kt.fromRandom(),s=n.toPublicKey(),a=i.mul(n),o=this.computeChallenge(e,i,r,a,s);return{R:s,SPrime:a,z:n.add(o.mul(t)).umod(this.curve.n)}}verifyProof(t,e,i,r){const{R:n,SPrime:s,z:a}=r,o=this.computeChallenge(t,e,i,s,n),c=this.curve.g.mul(a),h=n.add(t.mul(o));if(!c.eq(h))return!1;const d=e.mul(a),u=s.add(i.mul(o));return!!d.eq(u)}computeChallenge(t,e,i,n,s){const a=[...t.encode(!0),...e.encode(!0),...i.encode(!0),...n.encode(!0),...s.encode(!0)],o=q(a);return new r(o).umod(this.curve.n)}}const zt={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_SUBSTR:127,OP_SPLIT:127,OP_LEFT:128,OP_NUM2BIN:128,OP_RIGHT:129,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_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8: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 zt)zt[zt[t]]=t;const jt=zt;class Xt{chunks;static fromASM(t){const e=[],i=t.split(" ");let r=0;for(;r<i.length;){const t=i[r];let n,s=0;if(t.startsWith("OP_")&&void 0!==jt[t]&&(n=t,s=jt[t]),"0"===t)s=0,e.push({op:s}),r+=1;else if("-1"===t)s=jt.OP_1NEGATE,e.push({op:s}),r+=1;else if(void 0===n){let t=i[r];t.length%2!=0&&(t="0"+t);const n=W(t,"hex");if(G(n,"hex")!==t)throw new Error("invalid hex string in script");const a=n.length;a>=0&&a<jt.OP_PUSHDATA1?s=a:a<Math.pow(2,8)?s=jt.OP_PUSHDATA1:a<Math.pow(2,16)?s=jt.OP_PUSHDATA2:a<Math.pow(2,32)&&(s=jt.OP_PUSHDATA4),e.push({data:n,op:s}),r+=1}else s===jt.OP_PUSHDATA1||s===jt.OP_PUSHDATA2||s===jt.OP_PUSHDATA4?(e.push({data:W(i[r+2],"hex"),op:s}),r+=3):(e.push({op:s}),r+=1)}return new Xt(e)}static fromHex(t){if(0===t.length)return Xt.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.");return Xt.fromBinary(W(t,"hex"))}static fromBinary(t){t=[...t];const e=[];let i=0;const r=new rt(t);for(;!r.eof();){const t=r.readUInt8();if(t===jt.OP_RETURN&&0===i){e.push({op:t,data:r.read()});break}t===jt.OP_IF||t===jt.OP_NOTIF||t===jt.OP_VERIF||t===jt.OP_VERNOTIF?i++:t===jt.OP_ENDIF&&i--;let n=0,s=[];if(t>0&&t<jt.OP_PUSHDATA1)n=t,e.push({data:r.read(n),op:t});else if(t===jt.OP_PUSHDATA1){try{n=r.readUInt8(),s=r.read(n)}catch{r.read()}e.push({data:s,op:t})}else if(t===jt.OP_PUSHDATA2){try{n=r.readUInt16LE(),s=r.read(n)}catch{r.read()}e.push({data:s,op:t})}else if(t===jt.OP_PUSHDATA4){try{n=r.readUInt32LE(),s=r.read(n)}catch{r.read()}e.push({data:s,op:t})}else e.push({op:t})}return new Xt(e)}constructor(t=[]){this.chunks=t}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(){return G(this.toBinary(),"hex")}toBinary(){const t=new it;for(let e=0;e<this.chunks.length;e++){const i=this.chunks[e],r=i.op;if(t.writeUInt8(r),r===jt.OP_RETURN&&null!=i.data){t.write(i.data);break}null!=i.data&&(r<jt.OP_PUSHDATA1?t.write(i.data):r===jt.OP_PUSHDATA1?(t.writeUInt8(i.data.length),t.write(i.data)):r===jt.OP_PUSHDATA2?(t.writeUInt16LE(i.data.length),t.write(i.data)):r===jt.OP_PUSHDATA4&&(t.writeUInt32LE(i.data.length),t.write(i.data)))}return t.toArray()}writeScript(t){return this.chunks=this.chunks.concat(t.chunks),this}writeOpCode(t){return this.chunks.push({op:t}),this}setChunkOpCode(t,e){return this.chunks[t]={op:e},this}writeBn(t){if(t.cmpn(0)===jt.OP_0)this.chunks.push({op:jt.OP_0});else if(0===t.cmpn(-1))this.chunks.push({op:jt.OP_1NEGATE});else if(t.cmpn(1)>=0&&t.cmpn(16)<=0)this.chunks.push({op:t.toNumber()+jt.OP_1-1});else{const e=t.toSm("little");this.writeBin(e)}return this}writeBin(t){let e;if(t.length>0&&t.length<jt.OP_PUSHDATA1)e=t.length;else if(0===t.length)e=jt.OP_0;else if(t.length<Math.pow(2,8))e=jt.OP_PUSHDATA1;else if(t.length<Math.pow(2,16))e=jt.OP_PUSHDATA2;else{if(!(t.length<Math.pow(2,32)))throw new Error("You can't push that much data");e=jt.OP_PUSHDATA4}return this.chunks.push({data:t,op:e}),this}writeNumber(t){return this.writeBn(new r(t)),this}removeCodeseparators(){const t=[];for(let e=0;e<this.chunks.length;e++)this.chunks[e].op!==jt.OP_CODESEPARATOR&&t.push(this.chunks[e]);return this.chunks=t,this}findAndDelete(t){const e=t.toHex();for(let t=0;t<this.chunks.length;t++)e===new Xt([this.chunks[t]]).toHex()&&this.chunks.splice(t,1);return this}isPushOnly(){for(let t=0;t<this.chunks.length;t++)if(this.chunks[t].op>jt.OP_16)return!1;return!0}isLockingScript(){throw new Error("Not implemented")}isUnlockingScript(){throw new Error("Not implemented")}_chunkToString(t){const e=t.op;let i="";return i=void 0===t.data?`${i} ${jt[e]}`:`${i} ${$(t.data)}`,i}}class Gt extends Xt{isLockingScript(){return!0}isUnlockingScript(){return!1}}class Yt extends Xt{isLockingScript(){return!1}isUnlockingScript(){return!0}}const Jt=1073741824,Zt=Math.pow(2,31)-1,Qt=!0,te=Object.freeze(new r(-1).toScriptNum()),ee=Object.freeze(Array.from({length:17},((t,e)=>Object.freeze(new r(e).toScriptNum()))));class ie{sourceTXID;sourceOutputIndex;sourceSatoshis;lockingScript;transactionVersion;otherInputs;outputs;inputIndex;unlockingScript;inputSequence;lockTime;context;programCounter;lastCodeSeparator;stack;altStack;ifStack;memoryLimit;stackMem;altStackMem;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.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0,this.reset()}reset(){this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0}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,n=t[r],s=t[r+1];if(2!==n)return!1;if(0===s)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]||s>1&&0===t[a]&&!(128&t[a+1])||i+s+7!==t.length)}(t))return this.scriptEvaluationError("The signature format is invalid."),!1;try{const e=$t.fromChecksigFormat(t);if(!e.hasLowS())return this.scriptEvaluationError("The signature must have a low S value."),!1;if(!(e.scope&$t.SIGHASH_FORKID))return this.scriptEvaluationError("The signature must use SIGHASH_FORKID."),!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{bt.fromDER(t)}catch(t){return this.scriptEvaluationError("The public key is in an unknown format."),!1}return!0}verifySignature(t,e,i){const n=$t.format({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}),s=new r(H(n));return pt(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>Jt&&this.scriptEvaluationError(`Data push > 1073741824 bytes (pc=${this.programCounter}).`);const n=!this.ifStack.includes(!1);var s,a;if(n&&((s=i)===jt.OP_2MUL||s===jt.OP_2DIV||s===jt.OP_VERIF||s===jt.OP_VERNOTIF||s===jt.OP_VER)&&this.scriptEvaluationError(`This opcode is currently disabled. (Opcode: ${jt[i]}, PC: ${this.programCounter})`),n&&i>=0&&i<=jt.OP_PUSHDATA4)(function(t){const e=t.data,i=t.op;return!(Array.isArray(e)&&(0===e.length?i!==jt.OP_0:1===e.length&&e[0]>=1&&e[0]<=16?i!==jt.OP_1+(e[0]-1):1===e.length&&129===e[0]?i!==jt.OP_1NEGATE:e.length<=75?i!==e.length:e.length<=255?i!==jt.OP_PUSHDATA1:e.length<=65535&&i!==jt.OP_PUSHDATA2))})(e)||this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`),this.pushStack(Array.isArray(e.data)?e.data:[]);else if(n||i>=jt.OP_IF&&i<=jt.OP_ENDIF){let t,e,s,o,c,h,d,u,l,f,p,b,g,y,m,w,I,v,k,S,_,E,P,O,N,A;switch(i){case jt.OP_1NEGATE:this.pushStackCopy(te);break;case jt.OP_0:this.pushStackCopy(ee[0]);break;case jt.OP_1:case jt.OP_2:case jt.OP_3:case jt.OP_4:case jt.OP_5:case jt.OP_6:case jt.OP_7:case jt.OP_8:case jt.OP_9:case jt.OP_10:case jt.OP_11:case jt.OP_12:case jt.OP_13:case jt.OP_14:case jt.OP_15:case jt.OP_16:b=i-(jt.OP_1-1),this.pushStackCopy(ee[b]);break;case jt.OP_NOP:case jt.OP_NOP2:case jt.OP_NOP3:case jt.OP_NOP1:case jt.OP_NOP4:case jt.OP_NOP5:case jt.OP_NOP6:case jt.OP_NOP7:case jt.OP_NOP8:case jt.OP_NOP9:case jt.OP_NOP10:case jt.OP_NOP11:case jt.OP_NOP12:case jt.OP_NOP13:case jt.OP_NOP14:case jt.OP_NOP15:case jt.OP_NOP16:case jt.OP_NOP17:case jt.OP_NOP18:case jt.OP_NOP19:case jt.OP_NOP20:case jt.OP_NOP21:case jt.OP_NOP22:case jt.OP_NOP23:case jt.OP_NOP24:case jt.OP_NOP25:case jt.OP_NOP26:case jt.OP_NOP27:case jt.OP_NOP28:case jt.OP_NOP29:case jt.OP_NOP30:case jt.OP_NOP31:case jt.OP_NOP32:case jt.OP_NOP33:case jt.OP_NOP34:case jt.OP_NOP35:case jt.OP_NOP36:case jt.OP_NOP37:case jt.OP_NOP38:case jt.OP_NOP39:case jt.OP_NOP40:case jt.OP_NOP41:case jt.OP_NOP42:case jt.OP_NOP43:case jt.OP_NOP44:case jt.OP_NOP45:case jt.OP_NOP46:case jt.OP_NOP47:case jt.OP_NOP48:case jt.OP_NOP49:case jt.OP_NOP50:case jt.OP_NOP51:case jt.OP_NOP52:case jt.OP_NOP53:case jt.OP_NOP54:case jt.OP_NOP55:case jt.OP_NOP56:case jt.OP_NOP57:case jt.OP_NOP58:case jt.OP_NOP59:case jt.OP_NOP60:case jt.OP_NOP61:case jt.OP_NOP62:case jt.OP_NOP63:case jt.OP_NOP64:case jt.OP_NOP65:case jt.OP_NOP66:case jt.OP_NOP67:case jt.OP_NOP68:case jt.OP_NOP69:case jt.OP_NOP70:case jt.OP_NOP71:case jt.OP_NOP72:case jt.OP_NOP73:case jt.OP_NOP77:break;case jt.OP_IF:case jt.OP_NOTIF:y=!1,n&&(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(),y=this.castToBool(t),i===jt.OP_NOTIF&&(y=!y)),this.ifStack.push(y);break;case jt.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 jt.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop();break;case jt.OP_VERIFY:this.stack.length<1&&this.scriptEvaluationError("OP_VERIFY requires at least one item to be on the stack."),e=this.stackTop(),y=this.castToBool(e),y||this.scriptEvaluationError("OP_VERIFY requires the top stack value to be truthy."),this.popStack();break;case jt.OP_RETURN:"UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.ifStack=[],this.programCounter--;break;case jt.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 jt.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 jt.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 jt.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),e=this.stackTop(-2),s=this.stackTop(-1),this.pushStackCopy(e),this.pushStackCopy(s);break;case jt.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),e=this.stackTop(-3),s=this.stackTop(-2),o=this.stackTop(-1),this.pushStackCopy(e),this.pushStackCopy(s),this.pushStackCopy(o);break;case jt.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),e=this.stackTop(-4),s=this.stackTop(-3),this.pushStackCopy(e),this.pushStackCopy(s);break;case jt.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(),n=this.popStack(),s=this.popStack();this.pushStack(r),this.pushStack(i),this.pushStack(e),this.pushStack(t),this.pushStack(s),this.pushStack(n);break}case jt.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 jt.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 jt.OP_DEPTH:this.pushStack(new r(this.stack.length).toScriptNum());break;case jt.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),this.popStack();break;case jt.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 jt.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),s=this.popStack(),this.popStack(),this.pushStack(s);break;case jt.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 jt.OP_PICK:case jt.OP_ROLL:{this.stack.length<2&&this.scriptEvaluationError(`${jt[i]} requires at least two items to be on the stack.`),u=r.fromScriptNum(this.popStack(),Qt),b=u.toNumber(),(b<0||b>=this.stack.length)&&this.scriptEvaluationError(`${jt[i]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);const t=this.stack[this.stack.length-1-b];i===jt.OP_ROLL?(this.stack.splice(this.stack.length-1-b,1),this.stackMem-=t.length,this.pushStack(t)):this.pushStackCopy(t);break}case jt.OP_ROT:this.stack.length<3&&this.scriptEvaluationError("OP_ROT requires at least three items to be on the stack."),d=this.popStack(),h=this.popStack(),c=this.popStack(),this.pushStack(h),this.pushStack(d),this.pushStack(c);break;case jt.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 jt.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 jt.OP_SIZE:this.stack.length<1&&this.scriptEvaluationError("OP_SIZE requires at least one item to be on the stack."),this.pushStack(new r(this.stackTop().length).toScriptNum());break;case jt.OP_AND:case jt.OP_OR:case jt.OP_XOR:{this.stack.length<2&&this.scriptEvaluationError(`${jt[i]} requires at least two items on the stack.`),s=this.popStack(),e=this.popStack(),e.length!==s.length&&this.scriptEvaluationError(`${jt[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===jt.OP_AND?t[r]=e[r]&s[r]:i===jt.OP_OR?t[r]=e[r]|s[r]:t[r]=e[r]^s[r];this.pushStack(t);break}case jt.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 jt.OP_LSHIFT:case jt.OP_RSHIFT:{if(this.stack.length<2&&this.scriptEvaluationError(`${jt[i]} requires at least two items to be on the stack.`),f=r.fromScriptNum(this.popStack(),Qt),e=this.popStack(),b=f.toNumber(),b<0&&this.scriptEvaluationError(`${jt[i]} requires the top item on the stack not to be negative.`),0===e.length){this.pushStack([]);break}let t;l=new r(e),t=i===jt.OP_LSHIFT?l.ushln(b):l.ushrn(b);const n=t.toArray("le",e.length);this.pushStack(n);break}case jt.OP_EQUAL:case jt.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${jt[i]} requires at least two items to be on the stack.`),s=this.popStack(),e=this.popStack(),y=function(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}(e,s),this.pushStack(y?[1]:[]),i===jt.OP_EQUALVERIFY&&(y||this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."),this.popStack());break;case jt.OP_1ADD:case jt.OP_1SUB:case jt.OP_NEGATE:case jt.OP_ABS:case jt.OP_NOT:case jt.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${jt[i]} requires at least one item to be on the stack.`),u=r.fromScriptNum(this.popStack(),Qt),i){case jt.OP_1ADD:u=u.add(new r(1));break;case jt.OP_1SUB:u=u.sub(new r(1));break;case jt.OP_NEGATE:u=u.neg();break;case jt.OP_ABS:u.isNeg()&&(u=u.neg());break;case jt.OP_NOT:u=new r(0===u.cmpn(0)?1:0);break;case jt.OP_0NOTEQUAL:u=new r(0!==u.cmpn(0)?1:0)}this.pushStack(u.toScriptNum());break;case jt.OP_ADD:case jt.OP_SUB:case jt.OP_MUL:case jt.OP_DIV:case jt.OP_MOD:case jt.OP_BOOLAND:case jt.OP_BOOLOR:case jt.OP_NUMEQUAL:case jt.OP_NUMEQUALVERIFY:case jt.OP_NUMNOTEQUAL:case jt.OP_LESSTHAN:case jt.OP_GREATERTHAN:case jt.OP_LESSTHANOREQUAL:case jt.OP_GREATERTHANOREQUAL:case jt.OP_MIN:case jt.OP_MAX:{this.stack.length<2&&this.scriptEvaluationError(`${jt[i]} requires at least two items to be on the stack.`),s=this.popStack(),e=this.popStack(),f=r.fromScriptNum(s,Qt),l=r.fromScriptNum(e,Qt);let t=0;switch(i){case jt.OP_MUL:t=l.byteLength()+f.byteLength();break;case jt.OP_ADD:case jt.OP_SUB:t=Math.max(l.byteLength(),f.byteLength())+1;break;default:t=Math.max(l.byteLength(),f.byteLength())}this.ensureStackMem(t);let n=new r(0);switch(i){case jt.OP_ADD:n=l.add(f);break;case jt.OP_SUB:n=l.sub(f);break;case jt.OP_MUL:n=l.mul(f);break;case jt.OP_DIV:0===f.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),n=l.div(f);break;case jt.OP_MOD:0===f.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),n=l.mod(f);break;case jt.OP_BOOLAND:n=new r(0!==l.cmpn(0)&&0!==f.cmpn(0)?1:0);break;case jt.OP_BOOLOR:n=new r(0!==l.cmpn(0)||0!==f.cmpn(0)?1:0);break;case jt.OP_NUMEQUAL:case jt.OP_NUMEQUALVERIFY:n=new r(0===l.cmp(f)?1:0);break;case jt.OP_NUMNOTEQUAL:n=new r(0!==l.cmp(f)?1:0);break;case jt.OP_LESSTHAN:n=new r(l.cmp(f)<0?1:0);break;case jt.OP_GREATERTHAN:n=new r(l.cmp(f)>0?1:0);break;case jt.OP_LESSTHANOREQUAL:n=new r(l.cmp(f)<=0?1:0);break;case jt.OP_GREATERTHANOREQUAL:n=new r(l.cmp(f)>=0?1:0);break;case jt.OP_MIN:n=l.cmp(f)<0?l:f;break;case jt.OP_MAX:n=l.cmp(f)>0?l:f}this.pushStack(n.toScriptNum()),i===jt.OP_NUMEQUALVERIFY&&(this.castToBool(this.stackTop())||this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."),this.popStack());break}case jt.OP_WITHIN:this.stack.length<3&&this.scriptEvaluationError("OP_WITHIN requires at least three items to be on the stack."),p=r.fromScriptNum(this.popStack(),Qt),f=r.fromScriptNum(this.popStack(),Qt),l=r.fromScriptNum(this.popStack(),Qt),y=l.cmp(f)>=0&&l.cmp(p)<0,this.pushStack(y?[1]:[]);break;case jt.OP_RIPEMD160:case jt.OP_SHA1:case jt.OP_SHA256:case jt.OP_HASH160:case jt.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${jt[i]} requires at least one item to be on the stack.`),t=this.popStack();let e=[];i===jt.OP_RIPEMD160?(a=t,e=(new L).update(a,undefined).digest()):i===jt.OP_SHA1?e=(t=>(new M).update(t,void 0).digest())(t):i===jt.OP_SHA256?e=q(t):i===jt.OP_HASH160?e=K(t):i===jt.OP_HASH256&&(e=H(t)),this.pushStack(e);break}case jt.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case jt.OP_CHECKSIG:case jt.OP_CHECKSIGVERIFY:{this.stack.length<2&&this.scriptEvaluationError(`${jt[i]} requires at least two items to be on the stack.`),v=this.popStack(),I=this.popStack(),this.checkSignatureEncoding(I)&&this.checkPublicKeyEncoding(v)||this.scriptEvaluationError(`${jt[i]} requires correct encoding for the public key and signature.`);const t=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);if(w=new Xt(t),w.findAndDelete((new Xt).writeBin(I)),m=!1,I.length>0)try{k=$t.fromChecksigFormat(I),S=bt.fromDER(v),m=this.verifySignature(k,S,w)}catch(t){m=!1}this.pushStack(m?[1]:[]),i===jt.OP_CHECKSIGVERIFY&&(m||this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."),this.popStack());break}case jt.OP_CHECKMULTISIG:case jt.OP_CHECKMULTISIGVERIFY:{_=1,this.stack.length<_&&this.scriptEvaluationError(`${jt[i]} requires at least 1 item for nKeys.`),O=r.fromScriptNum(this.stackTop(-_),Qt).toNumber(),(O<0||O>Zt)&&this.scriptEvaluationError(`${jt[i]} requires a key count between 0 and ${Zt}.`),E=++_,_+=O,this.stack.length<_&&this.scriptEvaluationError(`${jt[i]} stack too small for nKeys and keys. Need ${_}, have ${this.stack.length}.`),N=r.fromScriptNum(this.stackTop(-_),Qt).toNumber(),(N<0||N>O)&&this.scriptEvaluationError(`${jt[i]} requires the number of signatures to be no greater than the number of keys.`),P=++_,_+=N,this.stack.length<_&&this.scriptEvaluationError(`${jt[i]} stack too small for N, keys, M, sigs, and dummy. Need ${_}, have ${this.stack.length}.`);const t=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);w=new Xt(t);for(let t=0;t<N;t++)I=this.stackTop(-P-t),w.findAndDelete((new Xt).writeBin(I));for(m=!0;m&&N>0;){if(0===O){m=!1;break}if(I=this.stackTop(-P),v=this.stackTop(-E),this.checkSignatureEncoding(I)&&this.checkPublicKeyEncoding(v)||this.scriptEvaluationError(`${jt[i]} requires correct encoding for the public key and signature.`),A=!1,I.length>0)try{k=$t.fromChecksigFormat(I),S=bt.fromDER(v),A=this.verifySignature(k,S,w)}catch(t){A=!1}A&&(P++,N--),E++,O--,N>O&&(m=!1)}let e=1+r.fromScriptNum(this.stackTop(-1),!1).toNumber()+1+r.fromScriptNum(this.stackTop(-(1+r.fromScriptNum(this.stackTop(-1),!1).toNumber()+1)),!1).toNumber()+1-1;for(;e>0;)this.popStack(),e--;this.stack.length<1&&this.scriptEvaluationError(`${jt[i]} requires an extra item (dummy) to be on the stack.`),this.popStack().length>0&&this.scriptEvaluationError(`${jt[i]} requires the extra stack item (dummy) to be empty.`),this.pushStack(m?[1]:[]),i===jt.OP_CHECKMULTISIGVERIFY&&(m||this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),this.popStack());break}case jt.OP_CAT:{this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),s=this.popStack(),e=this.popStack();const t=e.concat(s);t.length>Jt&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),this.pushStack(t);break}case jt.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();b=r.fromScriptNum(t,Qt).toNumber(),(b<0||b>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."),this.pushStack(e.slice(0,b)),this.pushStack(e.slice(b));break}case jt.OP_NUM2BIN:{this.stack.length<2&&this.scriptEvaluationError("OP_NUM2BIN requires at least two items to be on the stack."),g=r.fromScriptNum(this.popStack(),Qt).toNumber(),(g>Jt||g<0)&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes or negative size.");let t=this.popStack();if(t=nt(t),t.length>g&&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."),t.length===g){this.pushStack(t);break}const e=new Array(g).fill(0);let i=0;t.length>0&&(i=128&t[t.length-1],t[t.length-1]&=127);for(let i=0;i<t.length;i++)e[i]=t[i];0!==i&&(e[g-1]|=128),this.pushStack(e);break}case jt.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=nt(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}).`)}}return this.programCounter++,!0}validate(){for(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."),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){const e=`Context: ${this.context}, PC: ${this.programCounter}`,i=this.stack.map((t=>null!=t&&void 0!==t.length?$(t):null==t?"null/undef":"INVALID_STACK_ITEM")).join(", "),r=this.altStack.map((t=>null!=t&&void 0!==t.length?$(t):null==t?"null/undef":"INVALID_STACK_ITEM")).join(", "),n=`Stack: [${i}] (len: ${this.stack.length}, mem: ${this.stackMem})`,s=`AltStack: [${r}] (len: ${this.altStack.length}, mem: ${this.altStackMem})`,a=`IfStack: [${this.ifStack.join(", ")}]`;throw new Error(`Script evaluation error: ${t}\nTXID: ${this.sourceTXID}, OutputIdx: ${this.sourceOutputIndex}\n${e}\n${n}\n${s}\n${a}`)}}function re(t){if(null==t)throw new Error("must have value");return t}class ne{lock(t){let e;if("string"==typeof t){const i=et(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 Gt([{op:jt.OP_DUP},{op:jt.OP_HASH160},{op:e.length,data:e},{op:jt.OP_EQUALVERIFY},{op:jt.OP_CHECKSIG}])}unlock(t,e="all",i=!1,r,n){return{sign:async(s,a)=>{let o=$t.SIGHASH_FORKID;"all"===e&&(o|=$t.SIGHASH_ALL),"none"===e&&(o|=$t.SIGHASH_NONE),"single"===e&&(o|=$t.SIGHASH_SINGLE),i&&(o|=$t.SIGHASH_ANYONECANPAY);const c=s.inputs[a],h=s.inputs.filter(((t,e)=>e!==a)),d=c.sourceTXID??c.sourceTransaction?.id("hex");if(null==d||void 0===d)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(""===d)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(n||=c.sourceTransaction?.outputs[c.sourceOutputIndex].lockingScript,null==n)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");const u=$t.format({sourceTXID:d,sourceOutputIndex:re(c.sourceOutputIndex),sourceSatoshis:r,transactionVersion:s.version,otherInputs:h,inputIndex:a,outputs:s.outputs,inputSequence:re(c.sequence),subscript:n,lockTime:s.lockTime,scope:o}),l=t.sign(q(u)),f=new $t(l.r,l.s,o).toChecksigFormat(),p=t.toPublicKey().encode(!0);return new Yt([{op:f.length,data:f},{op:p.length,data:p}])},estimateLength:async()=>108}}}function se(t){if(null==t)throw new Error("must have value");return t}class ae{wallet;originator;static decode(t){const e=bt.fromString($(se(t.chunks[0].data))),i=[];for(let e=2;e<t.chunks.length;e++){const r=t.chunks[e+1]?.op;let n=t.chunks[e].data??[];if(0===n.length&&(t.chunks[e].op>=80&&t.chunks[e].op<=95?n=[t.chunks[e].op-80]:0===t.chunks[e].op?n=[0]:79===t.chunks[e].op&&(n=[129])),i.push(n),r===jt.OP_DROP||r===jt.OP_2DROP)break}return{fields:i,lockingPublicKey:e}}constructor(t,e){this.wallet=t,this.originator=e}async lock(t,e,i,r,n=!1,s=!0,a="before"){const{publicKey:o}=await this.wallet.getPublicKey({protocolID:e,keyID:i,counterparty:r,forSelf:n},this.originator),c=[],h=[];if(c.push({op:o.length/2,data:W(o,"hex")}),c.push({op:jt.OP_CHECKSIG}),s){const n=t.reduce(((t,e)=>[...t,...e]),[]),{signature:s}=await this.wallet.createSignature({data:n,protocolID:e,keyID:i,counterparty:r},this.originator);t.push(s)}for(const e of t)h.push(0===(d=e).length||1===d.length&&0===d[0]?{op:0}:1===d.length&&d[0]>0&&d[0]<=16?{op:80+d[0]}:1===d.length&&129===d[0]?{op:79}:d.length<=75?{op:d.length,data:d}:d.length<=255?{op:76,data:d}:d.length<=65535?{op:77,data:d}:{op:78,data:d});var d;let u=t.length;for(;u>1;)h.push({op:jt.OP_2DROP}),u-=2;return 0!==u&&h.push({op:jt.OP_DROP}),new Gt("before"===a?[...c,...h]:[...h,...c])}unlock(t,e,i,r="all",n=!1,s,a){return{sign:async(o,c)=>{let h=$t.SIGHASH_FORKID;"all"===r&&(h|=$t.SIGHASH_ALL),"none"===r&&(h|=$t.SIGHASH_NONE),"single"===r&&(h|=$t.SIGHASH_SINGLE),n&&(h|=$t.SIGHASH_ANYONECANPAY);const d=o.inputs[c],u=o.inputs.filter(((t,e)=>e!==c)),l=d.sourceTXID??d.sourceTransaction?.id("hex");if(null==l||void 0===l)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(s||=d.sourceTransaction?.outputs[d.sourceOutputIndex].satoshis,null==s||void 0===s)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(a||=d.sourceTransaction?.outputs[d.sourceOutputIndex].lockingScript,null==a)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");const f=$t.format({sourceTXID:l,sourceOutputIndex:se(d.sourceOutputIndex),sourceSatoshis:s,transactionVersion:o.version,otherInputs:u,inputIndex:c,outputs:o.outputs,inputSequence:d.sequence??4294967295,subscript:a,lockTime:o.lockTime,scope:h}),p=q(f),{signature:b}=await this.wallet.createSignature({data:p,protocolID:t,keyID:e,counterparty:i},this.originator),g=dt.fromDER([...b]),y=new $t(g.r,g.s,h).toChecksigFormat();return new Yt([{op:y.length,data:y}])},estimateLength:async()=>73}}}class oe{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 n=t.inputs[r];let s;if(i+=40,"object"==typeof n.unlockingScript)s=n.unlockingScript.toBinary().length;else{if("object"!=typeof n.unlockingScriptTemplate)throw new Error("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");s=await n.unlockingScriptTemplate.estimateLength(t,r)}i+=e(s),i+=s}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 ce{https;constructor(t){this.https=t}async request(t,e){return await new Promise(((i,r)=>{const n=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,n=t.headers["content-type"],s=""!==e&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(e):e;i({status:t.statusCode,statusText:t.statusMessage,ok:r,data:s})}))}));n.on("error",(t=>{r(t)})),null!==e.data&&void 0!==e.data&&n.write(JSON.stringify(e.data)),n.end()}))}}class he{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),n=r.headers.get("Content-Type"),s=n?.startsWith("application/json")?await r.json():await r.text();return{ok:r.ok,status:r.status,statusText:r.statusText,data:s}}}function de(){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 he(window.fetch.bind(window));if("undefined"==typeof require)return t;try{const t=require("https");return new ce(t)}catch(e){return t}}function ue(){return`ts-sdk-${$(mt(16))}`}class le{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(t,e){if(this.URL=t,"string"==typeof e)this.apiKey=e,this.httpClient=de(),this.deploymentId=ue(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const t=e??{},{apiKey:i,deploymentId:r,httpClient:n,callbackToken:s,callbackUrl:a,headers:o}=t;this.apiKey=i,this.httpClient=n??de(),this.deploymentId=r??ue(),this.callbackToken=s,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:n}=t.data,s={status:"success",txid:e,message:`${r} ${i}`};return null!=n&&(s.competingTxs=n),s}{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 fe{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??de(),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 pe{blockHeight;path;static fromHex(t){return pe.fromBinary(W(t,"hex"))}static fromReader(t,e=!0){const i=t.readVarIntNum(),r=t.readUInt8(),n=Array(r).fill(null).map((()=>[]));let s,a,o;for(let e=0;e<r;e++){for(o=t.readVarIntNum();o>0;){a=t.readVarIntNum(),s=t.readUInt8();const i={offset:a};1&s?i.duplicate=!0:(2&s&&(i.txid=!0),i.hash=$(t.read(32).reverse())),Array.isArray(n[e])&&0!==n[e].length||(n[e]=[]),n[e].push(i),o--}n[e].sort(((t,e)=>t.offset-e.offset))}return new pe(i,n,e)}static fromBinary(t){const e=new rt(t);return pe.fromReader(e)}static fromCoinbaseTxidAndHeight(t,e){return new pe(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 n;this.path.forEach(((t,e)=>{if(0===t.length&&0===e)throw new Error(`Empty level at height: ${e}`);const n=new Set;t.forEach((t=>{if(n.has(t.offset))throw new Error(`Duplicate offset: ${t.offset}, at height: ${e}`);if(n.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&&(n=this.computeRoot(t.hash)),n!==this.computeRoot(t.hash))throw new Error("Mismatched roots")}))}toBinary(){const t=new it;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(W(e.hash,"hex").reverse())}}return t.toArray()}toHex(){return $(this.toBinary())}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=>$(H(W(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 n=e>>t^1,s=this.findOrComputeLeaf(t,n);if("object"!=typeof s)throw new Error(`Missing hash for index ${e} at height ${t}`);r=!0===s.duplicate?i((r??"")+(r??"")):i(n%2!=0?(s.hash??"")+(r??""):(r??"")+(s.hash??""))}return r}findOrComputeLeaf(t,e){const i=t=>$(H(W(t,"hex").reverse()).reverse());let r=this.path[t].find((t=>t.offset===e));if(null!=r)return r;if(0===t)return;const n=t-1,s=e<<1,a=this.findOrComputeLeaf(n,s);if(null==a||null==a.hash||""===a.hash)return;const o=this.findOrComputeLeaf(n,s+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 n=e[i].find((e=>e.offset===t.path[i][r].offset));null!=n&&(n.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=[],n=[];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,s=this.path[0][e+(r?-1:1)];void 0!==s.txid&&null!==s.txid&&s.txid||t(s.offset,n)}}e(n,0);for(let t=1;t<this.path.length;t++)n=r,r=i(r),e(n,t)}}class be{_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=$(H(this._rawTx)),this._txid;throw new Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=Se.fromBinary(this._rawTx),this._tx):void 0}get rawTx(){return null!=this._rawTx?this._rawTx:null!=this._tx?(this._rawTx=this._tx.toBinary(),this._rawTx):void 0}constructor(t,e){"string"==typeof t?this._txid=t:Array.isArray(t)?this._rawTx=t:this._tx=t,this.bumpIndex=e,this.updateInputTxids()}static fromTx(t,e){return new be(t,e)}static fromRawTx(t,e){return new be(t,e)}static fromTxid(t,e){return new be(t,e)}updateInputTxids(){if(this.hasProof||null==this.tx)this.inputTxids=[];else{const t={};for(const e of this.tx.inputs)void 0!==e.sourceTXID&&null!==e.sourceTXID&&""!==e.sourceTXID&&(t[e.sourceTXID]=!0);this.inputTxids=Object.keys(t)}}toWriter(t,e){const i=e=>{t.writeUInt8(e)},r=()=>{if(null!=this._rawTx)t.write(this._rawTx);else{if(null==this._tx)throw new Error("a valid serialized Transaction is expected");t.write(this._tx.toBinary())}};e===me?this.isTxidOnly?(i(Ie.TXID_ONLY),(()=>{if(null==this._txid)throw new Error("Transaction ID (_txid) is undefined");t.writeReverse(W(this._txid,"hex"))})()):void 0!==this.bumpIndex?(i(Ie.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex),r()):(i(Ie.RAWTX),r()):(r(),(()=>{void 0===this.bumpIndex?i(Ie.RAWTX):(i(Ie.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex))})())}static fromReader(t,e){let i,r,n;if(e===me){const e=t.readUInt8();e===Ie.TXID_ONLY?n=be.fromTxid($(t.readReverse(32))):(e===Ie.RAWTX_AND_BUMP_INDEX&&(r=t.readVarIntNum()),i=Se.fromReader(t),n=be.fromTx(i,r))}else i=Se.fromReader(t),r=0!==t.readUInt8()?t.readVarIntNum():void 0,n=be.fromTx(i,r);return n}}function ge(t){if(null==t)throw new Error("Expected a valid value, but got undefined.");return t}const ye=4022206465,me=4022206466,we=16843009;var Ie,ve;!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"}(Ie||(Ie={}));class ke{bumps=[];txs=[];version=me;atomicTxid=void 0;constructor(t=me){this.version=t}findTxid(t){return this.txs.find((e=>e.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.txs.splice(e,1),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(ge(t.sourceTXID));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(ge(r.sourceTXID));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;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 n of i.path[0])if(n.hash===r){t.bumpIndex=e,n.txid=!0;break}}return e}mergeRawTx(t,e){const i=new be(t,e);return this.removeExistingTxid(i.txid),this.txs.push(i),this.tryToValidateBumpIndex(i),i}mergeTransaction(t){const e=t.id("hex");let i;this.removeExistingTxid(e),null!=t.merklePath&&(i=this.mergeBump(t.merklePath));const r=new be(t,i);if(this.txs.push(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.txs.splice(e,1)}mergeTxidOnly(t){let e=this.txs.find((e=>e.txid===t));return null==e&&(e=new be(t),this.txs.push(e),this.tryToValidateBumpIndex(e)),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=Array.isArray(t)?ke.fromBinary(t):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 n=(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,!n(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(){this.sortTxs();const t=new it;return this.toWriter(t),t.toArray()}toBinaryAtomic(t){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 it;return r.writeUInt32LE(we),r.writeReverse(W(t,"hex")),i.toWriter(r),r.toArray()}toHex(){return $(this.toBinary())}static fromReader(t){let e,i=t.readUInt32LE();if(i===we&&(e=$(t.readReverse(32)),i=t.readUInt32LE()),i!==ye&&i!==me)throw new Error(`Serialized BEEF must start with 4022206465 or ${me} but starts with ${i}`);const r=new ke(i),n=t.readVarIntNum();for(let e=0;e<n;e++){const e=pe.fromReader(t,!1);r.bumps.push(e)}const s=t.readVarIntNum();for(let e=0;e<s;e++){const e=be.fromReader(t,i);r.txs.push(e)}return r.atomicTxid=e,r}static fromBinary(t){const e=new rt(t);return ke.fromReader(e)}static fromString(t,e="hex"){const i=W(t,e),r=new rt(i);return ke.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=[],n=[];for(const s of this.txs)e[s.txid]=s,s.isValid=s.hasProof,s.isValid?(t[s.txid]=!0,r.push(s)):s.isTxidOnly&&0===s.inputTxids.length?(t[s.txid]=!0,n.push(s)):i.push(s);const s={},a=[],o=i;i=[];for(const t of o){let r=!1;for(const i of t.inputTxids)void 0===e[i]&&(s[i]=!0,r=!0);r?a.push(t):i.push(t)}for(;i.length>0;){const e=i;i=[];for(const n of e)n.inputTxids.every((e=>t[e]))?(t[n.txid]=!0,r.push(n)):i.push(n);if(e.length===i.length)break}const c=i;return this.txs=a.concat(c).concat(n).concat(r),{missingInputs:Object.keys(s),notValid:c.map((t=>t.txid)),valid:Object.keys(t),withMissingInputs:a.map((t=>t.txid)),txidOnly:n.map((t=>t.txid))}}clone(){const t=new ke;return t.version=this.version,t.bumps=Array.from(this.bumps),t.txs=Array.from(this.txs),t}trimKnownTxids(t){for(let e=0;e<this.txs.length;){const i=this.txs[e];i.isTxidOnly&&t.includes(i.txid)?this.txs.splice(e,1):e++}}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(){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 n=e.path[i-1].find((t=>t.offset===r.offset+1)),s=r.offset>>1;void 0!==n&&"string"==typeof n.hash&&e.path[i].every((t=>t.offset!==s))&&e.path[i].push({offset:s,hash:(t=n.hash+r.hash,$(H(W(t,"hex").reverse()).reverse()))})}var t}}class Se{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;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}=Se.fromAnyBeef(t,e);return i}static fromAtomicBEEF(t){const{tx:e,txid:i,beef:r}=Se.fromAnyBeef(t);if(i!==r.atomicTxid)throw 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=ke.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,n=i.findAtomicTransaction(r);if(null==n)throw e?new Error(`Transaction with TXID ${r} not found in BEEF data.`):new Error("beef does not contain transaction for atomic txid.");return{tx:n,beef:i,txid:r}}static fromEF(t){const e=new rt(t),i=e.readUInt32LE();if("0000000000ef"!==$(e.read(6)))throw new Error("Invalid EF marker");const r=e.readVarIntNum(),n=[];for(let t=0;t<r;t++){const t=$(e.readReverse(32)),i=e.readUInt32LE(),r=e.readVarIntNum(),s=e.read(r),a=Yt.fromBinary(s),o=e.readUInt32LE(),c=e.readUInt64LEBn().toNumber(),h=e.readVarIntNum(),d=e.read(h),u=Gt.fromBinary(d),l=new Se(void 0,[],[],void 0);l.outputs=Array(i+1).fill(null),l.outputs[i]={satoshis:c,lockingScript:u},n.push({sourceTransaction:l,sourceTXID:t,sourceOutputIndex:i,unlockingScript:a,sequence:o})}const s=e.readVarIntNum(),a=[];for(let t=0;t<s;t++){const t=e.readUInt64LEBn().toNumber(),i=e.readVarIntNum(),r=e.read(i),n=Gt.fromBinary(r);a.push({satoshis:t,lockingScript:n})}const o=e.readUInt32LE();return new Se(i,n,a,o)}static parseScriptOffsets(t){const e=new rt(t),i=[],r=[];e.pos+=4;const n=e.readVarIntNum();for(let t=0;t<n;t++){e.pos+=36;const r=e.readVarIntNum();i.push({vin:t,offset:e.pos,length:r}),e.pos+=r+4}const s=e.readVarIntNum();for(let t=0;t<s;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=$(t.readReverse(32)),i=t.readUInt32LE(),n=t.readVarIntNum(),s=t.read(n),a=Yt.fromBinary(s),o=t.readUInt32LE();r.push({sourceTXID:e,sourceOutputIndex:i,unlockingScript:a,sequence:o})}const n=t.readVarIntNum(),s=[];for(let e=0;e<n;e++){const e=t.readUInt64LEBn().toNumber(),i=t.readVarIntNum(),r=t.read(i),n=Gt.fromBinary(r);s.push({satoshis:e,lockingScript:n})}const a=t.readUInt32LE();return new Se(e,r,s,a)}static fromBinary(t){const e=new rt(t);return Se.fromReader(e)}static fromHex(t){return Se.fromBinary(W(t,"hex"))}static fromHexEF(t){return Se.fromEF(W(t,"hex"))}static fromHexBEEF(t,e){return Se.fromBEEF(W(t,"hex"),e)}constructor(t=1,e=[],i=[],r=0,n=new Map,s){this.version=t,this.inputs=e,this.outputs=i,this.lockTime=r,this.metadata=n,this.merklePath=s}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.cachedHash=void 0,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 ne).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=new oe(1),e="equal"){if(this.cachedHash=void 0,"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 n=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);n[t]=n[t]+e,i+=e,r-=e}for(const t of this.outputs)!0===t.change&&(t.satoshis=n.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.cachedHash=void 0;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 le(t?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",e)}()){return await t.broadcast(this)}toBinary(){const t=new it;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(W(e.sourceTXID,"hex"));if(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??0)}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)}return t.writeUInt32LE(this.lockTime),t.toArray()}toEF(){const t=new it;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(W(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??0),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)}return t.writeUInt32LE(this.lockTime),t.toArray()}toHexEF(){return $(this.toEF())}toHex(){return $(this.toBinary())}toHexBEEF(){return $(this.toBEEF())}toHexAtomicBEEF(){return $(this.toAtomicBEEF())}hash(t){let e;return null!=this.cachedHash?e=this.cachedHash:(e=H(this.toBinary()),this.cachedHash=e),"hex"===t?$(e):e}id(t){const e=[...this.hash()];return e.reverse(),"hex"===t?$(e):e}async verify(t=function(){return new fe}(),e,i){const r=new Set,n=[this];for(;n.length>0;){const s=n.shift(),a=s?.id("hex")??"";if(null!=a&&""!==a&&r.has(a))continue;if("object"==typeof s?.merklePath){if("scripts only"===t){null!=a&&r.add(a);continue}if(await s.merklePath.verify(a,t)){r.add(a);continue}}if(void 0!==e){if(void 0===s)throw new Error("Transaction is undefined");const t=Se.fromEF(s.toEF());if(delete t.outputs[0].satoshis,t.outputs[0].change=!0,await t.fee(e),s.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===s)throw new Error("Transaction is undefined");for(let t=0;t<s.inputs.length;t++){const e=s.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)||n.push(e.sourceTransaction);const d=s.inputs.filter(((e,i)=>i!==t));if(void 0===e.sourceTXID&&(e.sourceTXID=h),!new ie({sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:s.version,otherInputs:d,unlockingScript:e.unlockingScript,inputSequence:e.sequence??0,inputIndex:t,outputs:s.outputs,lockTime:s.lockTime,memoryLimit:i}).validate())return!1}let c=0;for(const t of s.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}toBEEF(t){const e=new it;e.writeUInt32LE(ye);const i=[],r=[],n=e=>{const s={tx:e},a="object"==typeof e.merklePath;if(a){let t=!1;for(let r=0;r<i.length;r++){if(i[r]===e.merklePath){s.pathIndex=r,t=!0;break}if(null!==e.merklePath&&void 0!==e.merklePath&&i[r].blockHeight===e.merklePath.blockHeight&&i[r].computeRoot()===e.merklePath.computeRoot()){i[r].combine(e.merklePath),s.pathIndex=r,t=!0;break}}t||(s.pathIndex=i.length,null!==e.merklePath&&void 0!==e.merklePath&&i.push(e.merklePath))}if(r.some((t=>t.tx.id("hex")===e.id("hex")))||r.unshift(s),!a)for(let i=0;i<e.inputs.length;i++){const r=e.inputs[i];if("object"==typeof r.sourceTransaction)n(r.sourceTransaction);else if(!1===t)throw new Error("A required source transaction is missing!")}};n(this),e.writeVarIntNum(i.length);for(const t of i)e.write(t.toBinary());e.writeVarIntNum(r.length);for(const t of r)e.write(t.tx.toBinary()),"number"==typeof t.pathIndex?(e.writeUInt8(1),e.writeVarIntNum(t.pathIndex)):e.writeUInt8(0);return e.toArray()}toAtomicBEEF(t){const e=new it;e.writeUInt32LE(16843009),e.write(this.hash());const i=this.toBEEF(t);return e.write(i),e.toArray()}}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"}(ve||(ve={}));class _e{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(t,e,i){this.cacheSharedSecret=e,this.retrieveCachedSharedSecret=i,this.anyone=new kt(1).toPublicKey(),this.rootKey="anyone"===t?new kt(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){"anyone"===i&&(i=this.anyone),i=this.normalizeCounterparty(i);const r=this.derivePublicKey(t,e,i),n=this.derivePrivateKey(t,e,i);return new Ut(n.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),n=W(this.computeInvoiceNumber(e,i),"utf8");return U(r.encode(!0),n)}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 kt(1).toPublicKey():"string"==typeof t?bt.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 Ee{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(t,e){this.rootKey="anyone"===t?new kt(1):t,this.keyDeriver=new _e(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 n=this.generateCacheKey("derivePublicKey",t,e,i,r);if(this.cache.has(n)){const t=this.cacheGet(n);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.derivePublicKey(t,e,i,r);return this.cacheSet(n,s),s}}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 n=this.keyDeriver.derivePrivateKey(t,e,i);return this.cacheSet(r,n),n}}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 n=this.keyDeriver.deriveSymmetricKey(t,e,i);return this.cacheSet(r,n),n}}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 n=this.keyDeriver.revealSpecificSecret(t,e,i);return this.cacheSet(r,n),n}}generateCacheKey(t,...e){return`${t}|${e.map((t=>this.serializeArgument(t))).join("|")}`}serializeArgument(t){return t instanceof bt||t instanceof kt?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 Pe=class{keyDeriver;constructor(t){"string"!=typeof t.identityKey&&(t=new Ee(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 Wt).generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),bt.fromString(t.counterparty),ot.fromDER(i)),n=[...r.R.encode(!0),...r.SPrime.encode(!0),...r.z.toArray()],s=(new Date).toISOString(),{ciphertext:a}=await this.encrypt({plaintext:i,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:t.verifier}),{ciphertext:o}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:t.verifier});return{prover:e,verifier:t.verifier,counterparty:t.counterparty,revelationTime:s,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:n}=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:n,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){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:U(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=U(e.toArray(),t.data).toString()===t.hmac.toString();if(!i){const t=new Error("HMAC is not valid");throw t.code="ERR_INVALID_HMAC",t}return{valid:i}}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??q(t.data??[]),i=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePrivateKey(t.protocolID,t.keyID,t.counterparty??"anyone");return{signature:ft(new r(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??q(t.data??[]),i=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePublicKey(t.protocolID,t.keyID,t.counterparty??"self",t.forSelf),n=pt(new r(e),dt.fromDER(t.signature),i);if(!n){const t=new Error("Signature is not valid");throw t.code="ERR_INVALID_SIGNATURE",t}return{valid:n}}};class Oe{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 Ne 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)}}var Ae,xe,Te;!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"}(Ae||(Ae={}));class Ce{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 n=Y(mt(12)),s=t=>{if("CWI"===t.data.type&&t.isTrusted&&t.data.id===n&&!0!==t.data.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",s),"error"===t.data.status){const e=new Ne(t.data.description,t.data.code);r(e)}else i(t.data.result)};window.addEventListener("message",s),window.parent.postMessage({type:"CWI",isInvocation:!0,id:n,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 Fe{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(t,e,i,r,n,s,a){this.type=t,this.serialNumber=e,this.subject=i,this.certifier=r,this.revocationOutpoint=n,this.fields=s,this.signature=a}toBinary(t=!0){const e=new it,i=W(this.type,"base64");e.write(i);const r=W(this.serialNumber,"base64");e.write(r);const n=W(this.subject,"hex");e.write(n);const s=W(this.certifier,"hex");e.write(s);const[a,o]=this.revocationOutpoint.split("."),c=W(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=W(t,"utf8");e.writeVarIntNum(r.length),e.write(r);const n=W(i,"utf8");e.writeVarIntNum(n.length),e.write(n)}if(t&&(this.signature??"").length>0){const t=W(this.signature,"hex");e.write(t)}return e.toArray()}static fromBinary(t){const e=new rt(t),i=Y(e.read(32)),r=Y(e.read(32)),n=e.read(33),s=$(n),a=e.read(33),o=$(a),c=e.read(32),h=`${$(c)}.${e.readVarIntNum()}`,d=e.readVarIntNum(),u={};for(let t=0;t<d;t++){const t=e.readVarIntNum(),i=e.read(t),r=X(i),n=e.readVarIntNum(),s=e.read(n),a=X(s);u[r]=a}let l;if(!e.eof()){const t=e.read();l=dt.fromDER(t).toString("hex")}return new Fe(i,r,s,o,h,u,l)}async verify(){const t=new Pe("anyone"),e=this.toBinary(!1),i=this.signature??"",{valid:r}=await t.verifySignature({signature:W(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=$(i)}static getCertificateFieldEncryptionDetails(t,e){return{protocolID:[2,"certificate field encryption"],keyID:e?`${e} ${t}`:t}}}(Te=xe||(xe={}))[Te.createAction=1]="createAction",Te[Te.signAction=2]="signAction",Te[Te.abortAction=3]="abortAction",Te[Te.listActions=4]="listActions",Te[Te.internalizeAction=5]="internalizeAction",Te[Te.listOutputs=6]="listOutputs",Te[Te.relinquishOutput=7]="relinquishOutput",Te[Te.getPublicKey=8]="getPublicKey",Te[Te.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",Te[Te.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",Te[Te.encrypt=11]="encrypt",Te[Te.decrypt=12]="decrypt",Te[Te.createHmac=13]="createHmac",Te[Te.verifyHmac=14]="verifyHmac",Te[Te.createSignature=15]="createSignature",Te[Te.verifySignature=16]="verifySignature",Te[Te.acquireCertificate=17]="acquireCertificate",Te[Te.listCertificates=18]="listCertificates",Te[Te.proveCertificate=19]="proveCertificate",Te[Te.relinquishCertificate=20]="relinquishCertificate",Te[Te.discoverByIdentityKey=21]="discoverByIdentityKey",Te[Te.discoverByAttributes=22]="discoverByAttributes",Te[Te.isAuthenticated=23]="isAuthenticated",Te[Te.waitForAuthentication=24]="waitForAuthentication",Te[Te.getHeight=25]="getHeight",Te[Te.getHeaderForHeight=26]="getHeaderForHeight",Te[Te.getNetwork=27]="getNetwork",Te[Te.getVersion=28]="getVersion";const Re=xe;class Be{wire;constructor(t){this.wire=t}async transmit(t,e="",i=[]){const r=new it;r.writeUInt8(Re[t]);const n=W(e,"utf8");r.writeUInt8(n.length),r.write(n),i.length>0&&r.write(i);const s=r.toArray(),a=await this.wire.transmitToWallet(s),o=new rt(a),c=o.readUInt8();if(0===c)return o.read();{const t=o.readVarIntNum(),e=o.read(t),i=X(e),r=o.readVarIntNum(),n=o.read(r),s=X(n);throw new Ne(i,c,s)}}async createAction(t,e){const i=new it,r=W(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=W(e.unlockingScript,"hex");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1),i.writeVarIntNum(e.unlockingScriptLength??0);const t=W(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=W(e.lockingScript,"hex");i.writeVarIntNum(t.length),i.write(t),i.writeVarIntNum(e.satoshis);const r=W(e.outputDescription,"utf8");if(i.writeVarIntNum(r.length),i.write(r),null!=e.basket&&""!==e.basket){const t=W(e.basket,"utf8");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1);if(null!=e.customInstructions&&""!==e.customInstructions){const t=W(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=W(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=W(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=W(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=W(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 n=await this.transmit("createAction",e,i.toArray()),s=new rt(n),a={};if(1===s.readInt8()){const t=s.read(32);a.txid=$(t)}if(1===s.readInt8()){const t=s.readVarIntNum();a.tx=s.read(t)}const o=s.readVarIntNum();if(o>=0){a.noSendChange=[];for(let t=0;t<o;t++){const t=this.readOutpoint(s);a.noSendChange.push(t)}}const c=s.readVarIntNum();if(c>=0){a.sendWithResults=[];for(let t=0;t<c;t++){const t=s.read(32),e=$(t),i=s.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===s.readInt8()){const t=s.readVarIntNum(),e=s.read(t),i=s.readVarIntNum(),r=s.read(i);a.signableTransaction={tx:e,reference:Y(r)}}return a}async signAction(t,e){const i=new it,r=Object.keys(t.spends);i.writeVarIntNum(r.length);for(const e of r){i.writeVarIntNum(Number(e));const r=t.spends[Number(e)],n=W(r.unlockingScript,"hex");i.writeVarIntNum(n.length),i.write(n),"number"==typeof r.sequenceNumber?i.writeVarIntNum(r.sequenceNumber):i.writeVarIntNum(-1)}const n=W(t.reference,"base64");if(i.writeVarIntNum(n.length),i.write(n),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=W(e,"hex");i.write(t)}}else i.writeVarIntNum(-1);else i.writeInt8(0);const s=await this.transmit("signAction",e,i.toArray()),a=new rt(s),o={};if(1===a.readInt8()){const t=a.read(32);o.txid=$(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=$(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,W(t.reference,"base64")),{aborted:!0}}async listActions(t,e){const i=new it;i.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=W(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 n=await this.transmit("listActions",e,i.toArray()),s=new rt(n),a=s.readVarIntNum(),o=[];for(let t=0;t<a;t++){const t=s.read(32),e=$(t),i=s.readVarIntNum(),r=s.readInt8();let n;switch(r){case 1:n="completed";break;case 2:n="unprocessed";break;case 3:n="sending";break;case 4:n="unproven";break;case 5:n="unsigned";break;case 6:n="nosend";break;case 7:n="nonfinal";break;case 8:n="failed";break;default:throw new Error(`Unknown status code: ${r}`)}const a=1===s.readInt8(),c=s.readVarIntNum(),h=s.read(c),d={txid:e,satoshis:i,status:n,isOutgoing:a,description:X(h),version:0,lockTime:0},u=s.readVarIntNum();if(u>=0){d.labels=[];for(let t=0;t<u;t++){const t=s.readVarIntNum(),e=s.read(t);d.labels.push(X(e))}}d.version=s.readVarIntNum(),d.lockTime=s.readVarIntNum();const l=s.readVarIntNum();if(l>=0){d.inputs=[];for(let t=0;t<l;t++){const t=this.readOutpoint(s),e=s.readVarIntNum(),i=s.readVarIntNum();let r;if(i>=0){const t=s.read(i);r=$(t)}const n=s.readVarIntNum();let a;if(n>=0){const t=s.read(n);a=$(t)}const o=s.readVarIntNum(),c=s.read(o),h=X(c),u=s.readVarIntNum();d.inputs.push({sourceOutpoint:t,sourceSatoshis:e,sourceLockingScript:r,unlockingScript:a,inputDescription:h,sequenceNumber:u})}}const f=s.readVarIntNum();if(f>=0){d.outputs=[];for(let t=0;t<f;t++){const t=s.readVarIntNum(),e=s.readVarIntNum(),i=s.readVarIntNum();let r;if(i>=0){const t=s.read(i);r=$(t)}const n=1===s.readInt8(),a=s.readVarIntNum(),o=s.read(a),c=X(o),h=s.readVarIntNum();let u;if(h>=0){const t=s.read(h);u=X(t)}const l=s.readVarIntNum(),f=[];if(l>=0)for(let t=0;t<l;t++){const t=s.readVarIntNum(),e=s.read(t);f.push(X(e))}const p=s.readVarIntNum();let b;if(p>=0){const t=s.read(p);b=X(t)}d.outputs.push({outputIndex:t,satoshis:e,lockingScript:r,spendable:n,outputDescription:c,basket:u,tags:f,customInstructions:b})}}o.push(d)}return{totalActions:a,actions:o}}async internalizeAction(t,e){const i=new it;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(W(e.paymentRemittance.senderIdentityKey,"hex"));const t=W(e.paymentRemittance.derivationPrefix,"base64");i.writeVarIntNum(t.length),i.write(t);const r=W(e.paymentRemittance.derivationSuffix,"base64");i.writeVarIntNum(r.length),i.write(r)}else{i.writeUInt8(2);const t=W(e.insertionRemittance?.basket,"utf8");if(i.writeVarIntNum(t.length),i.write(t),"string"==typeof e.insertionRemittance?.customInstructions&&""!==e.insertionRemittance.customInstructions){const t=W(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=W(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=W(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}}else i.writeVarIntNum(-1);const r=W(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 it,r=W(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=W(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 n=await this.transmit("listOutputs",e,i.toArray()),s=new rt(n),a=s.readVarIntNum(),o=s.readVarIntNum();let c;o>=0&&(c=s.read(o));const h=[];for(let t=0;t<a;t++){const t={spendable:!0,outpoint:this.readOutpoint(s),satoshis:s.readVarIntNum()},e=s.readVarIntNum();e>=0&&(t.lockingScript=$(s.read(e)));const i=s.readVarIntNum();i>=0&&(t.customInstructions=X(s.read(i)));const r=s.readVarIntNum();if(-1!==r){const e=[];for(let t=0;t<r;t++){const t=s.readVarIntNum();e.push(X(s.read(t)))}t.tags=e}const n=s.readVarIntNum();if(-1!==n){const e=[];for(let t=0;t<n;t++){const t=s.readVarIntNum();e.push(X(s.read(t)))}t.labels=e}h.push(t)}return{totalOutputs:a,BEEF:c,outputs:h}}async relinquishOutput(t,e){const i=new it,r=W(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 it,[i,r]=t.split(".");return e.write(W(i,"hex")),e.writeVarIntNum(Number(r)),e.toArray()}readOutpoint(t){return`${$(t.read(32))}.${t.readVarIntNum()}`}async getPublicKey(t,e){const i=new it;i.writeUInt8(t.identityKey?1:0),t.identityKey?i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)):(i.write(this.encodeKeyRelatedParams(t.protocolID??=[ve.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:$(r)}}async revealCounterpartyKeyLinkage(t,e){const i=new it;i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),i.write(W(t.counterparty,"hex")),i.write(W(t.verifier,"hex"));const r=await this.transmit("revealCounterpartyKeyLinkage",e,i.toArray()),n=new rt(r),s=$(n.read(33)),a=$(n.read(33)),o=$(n.read(33)),c=n.readVarIntNum(),h=X(n.read(c)),d=n.readVarIntNum(),u=n.read(d),l=n.readVarIntNum();return{prover:s,verifier:a,counterparty:o,revelationTime:h,encryptedLinkage:u,encryptedLinkageProof:n.read(l)}}async revealSpecificKeyLinkage(t,e){const i=new it;i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.write(W(t.verifier,"hex"));const r=await this.transmit("revealSpecificKeyLinkage",e,i.toArray()),n=new rt(r),s=$(n.read(33)),a=$(n.read(33)),o=$(n.read(33)),c=n.readUInt8(),h=n.readVarIntNum(),d=X(n.read(h)),u=n.readVarIntNum(),l=X(n.read(u)),f=n.readVarIntNum(),p=n.read(f),b=n.readVarIntNum();return{prover:s,verifier:a,counterparty:o,protocolID:[c,d],keyID:l,encryptedLinkage:p,encryptedLinkageProof:n.read(b),proofType:n.readUInt8()}}async encrypt(t,e){const i=new it;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 it;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 it;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 it;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 it;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 it;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,n){const s=new it;s.writeUInt8(t[0]);const a=W(t[1],"utf8");s.writeVarIntNum(a.length),s.write(a);const o=W(e,"utf8");return s.writeVarIntNum(o.length),s.write(o),"string"!=typeof i?s.writeUInt8(0):"self"===i?s.writeUInt8(11):"anyone"===i?s.writeUInt8(12):s.write(W(i,"hex")),s.write(this.encodePrivilegedParams(r,n)),s.toArray()}async acquireCertificate(t,e){const i=new it;i.write(W(t.type,"base64")),i.write(W(t.certifier,"hex"));const r=Object.entries(t.fields);i.writeVarIntNum(r.length);for(const[t,e]of r){const r=W(t,"utf8"),n=W(e,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(n.length),i.write(n)}if(i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),i.writeUInt8("direct"===t.acquisitionProtocol?1:2),"direct"===t.acquisitionProtocol){i.write(W(t.serialNumber,"base64")),i.write(this.encodeOutpoint(t.revocationOutpoint??""));const e=W(t.signature,"hex");i.writeVarIntNum(e.length),i.write(e);const r="certifier"!==t.keyringRevealer?W(t.keyringRevealer,"hex"):[11];i.write(r);const n=Object.keys(t.keyringForSubject??{});i.writeVarIntNum(n.length);for(let e=0;e<n.length;e++){const r=W(n[e],"utf8");i.writeVarIntNum(r.length),i.write(r);const s=W(t.keyringForSubject?.[n[e]],"base64");i.writeVarIntNum(s.length),i.write(s)}}else{const e=W(t.certifierUrl,"utf8");i.writeVarIntNum(e.length),i.write(e)}const n=await this.transmit("acquireCertificate",e,i.toArray()),s=Fe.fromBinary(n);return{...s,signature:s.signature}}encodePrivilegedParams(t,e){const i=new it;if("boolean"==typeof t?i.writeInt8(t?1:0):i.writeInt8(-1),"string"==typeof e){const t=W(e,"utf8");i.writeInt8(t.length),i.write(t)}else i.writeInt8(-1);return i.toArray()}async listCertificates(t,e){const i=new it;i.writeVarIntNum(t.certifiers.length);for(let e=0;e<t.certifiers.length;e++)i.write(W(t.certifiers[e],"hex"));i.writeVarIntNum(t.types.length);for(let e=0;e<t.types.length;e++)i.write(W(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()),n=new rt(r),s=n.readVarIntNum(),a=[];for(let t=0;t<s;t++){const t=n.readVarIntNum(),e=n.read(t),i=Fe.fromBinary(e);a.push({...i,signature:i.signature})}return{totalCertificates:s,certificates:a}}async proveCertificate(t,e){const i=new it,r=W(t.certificate.type,"base64");i.write(r);const n=W(t.certificate.subject,"hex");i.write(n);const s=W(t.certificate.serialNumber,"base64");i.write(s);const a=W(t.certificate.certifier,"hex");i.write(a);const o=this.encodeOutpoint(t.certificate.revocationOutpoint??"");i.write(o);const c=W(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=W(t,"utf8"),n=W(e,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(n.length),i.write(n)}i.writeVarIntNum(t.fieldsToReveal.length);for(const e of t.fieldsToReveal){const t=W(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}i.write(W(t.verifier,"hex")),i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason));const d=await this.transmit("proveCertificate",e,i.toArray()),u=new rt(d),l=u.readVarIntNum(),f={};for(let t=0;t<l;t++){const t=u.readVarIntNum(),e=X(u.read(t)),i=u.readVarIntNum();f[e]=Y(u.read(i))}return{keyringForVerifier:f}}async relinquishCertificate(t,e){const i=new it,r=W(t.type,"base64");i.write(r);const n=W(t.serialNumber,"base64");i.write(n);const s=W(t.certifier,"hex");return i.write(s),await this.transmit("relinquishCertificate",e,i.toArray()),{relinquished:!0}}parseDiscoveryResult(t){const e=new rt(t),i=e.readVarIntNum(),r=[];for(let t=0;t<i;t++){const t=e.readVarIntNum(),i=e.read(t),n=Fe.fromBinary(i),s=e.readVarIntNum(),a=X(e.read(s)),o=e.readVarIntNum(),c=X(e.read(o)),h=e.readVarIntNum(),d=X(e.read(h)),u=e.readUInt8(),l={},f=e.readVarIntNum();for(let t=0;t<f;t++){const t=e.readVarIntNum(),i=X(e.read(t)),r=e.readVarIntNum();l[i]=e.read(r)}const p={},b=e.readVarIntNum();for(let t=0;t<b;t++){const t=e.readVarIntNum(),i=X(e.read(t)),r=e.readVarIntNum();p[i]=X(e.read(r))}r.push({...n,signature:n.signature,certifierInfo:{iconUrl:c,name:a,description:d,trust:u},publiclyRevealedKeyring:l,decryptedFields:p})}return{totalCertificates:i,certificates:r}}async discoverByIdentityKey(t,e){const i=new it;i.write(W(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 it,r=Object.keys(t.attributes);i.writeVarIntNum(r.length);for(let e=0;e<r.length;e++)i.writeVarIntNum(r[e].length),i.write(W(r[e],"utf8")),i.writeVarIntNum(t.attributes[r[e]].length),i.write(W(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 n=await this.transmit("discoverByAttributes",e,i.toArray());return this.parseDiscoveryResult(n)}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 rt(i).readVarIntNum()}}async getHeaderForHeight(t,e){const i=new it;i.writeVarIntNum(t.height);const r=await this.transmit("getHeaderForHeight",e,i.toArray());return{header:$(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:X(i)}}}class Le{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 rt(t),i=e.readUInt8(),r=Re[i];if(void 0===r||""===r)throw new Error(`Invalid call code: ${i}`);const n=e.readUInt8();let s;if(n>0){const t=e.read(n);s=X(t)}const a=e.read(),o=await fetch(`${this.baseUrl}/${r}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:s??""},body:new Uint8Array(a)}),c=await o.arrayBuffer();return Array.from(new Uint8Array(c))}}class De extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(t,e,i,r,n){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=t,this.sendWithResults=e,this.txid=i,this.tx=r,this.noSendChange=n,this.code=5,this.name=this.constructor.name}}class Me{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 n=!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!==n||console.error("Originator is required in Node.js environments");const s=await await i(`${this.baseUrl}/${t}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...n?{Origin:n}:{},...n?{Originator:n}:{}},body:JSON.stringify(e)}),a=await s.json();if(!s.ok){if(400===s.status&&a.isError&&5===a.code)throw new De(a.reviewActionResults,a.sendWithResults,a.txid,a.tx,a.noSendChange);{const i={call:t,args:e,message:a.message??`HTTP Client error ${s.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 Ve{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 n=Y(mt(12)),s=t=>{const e=JSON.parse(t.data);if("CWI"===e.type&&e.id===n&&!0!==e.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",s),"error"===e.status){const t=new Ne(e.description,e.code);r(t)}else i(e.result)};window.addEventListener("message",s),window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:n,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)}}class qe{substrate;originator;constructor(t="auto",e){"Cicada"===t&&(t=new Be(new Le(e))),"window.CWI"===t&&(t=new Oe),"XDM"===t&&(t=new Ce),"json-api"===t&&(t=new Me(e)),"react-native"===t&&(t=new Ve(e)),this.substrate=t,this.originator=e}async connectToSubstrate(){if("object"==typeof this.substrate)return;let t;const e=async e=>{let i;if(i="number"==typeof e?await Promise.race([t.getVersion({}),new Promise(((t,i)=>setTimeout((()=>i(new Error("Timed out."))),e)))]):await t.getVersion({}),"object"!=typeof i||"string"!=typeof i.version)throw new Error("Failed to use substrate.")};try{t=new Oe,await e(),this.substrate=t}catch(i){try{t=new Ce,await e(200),this.substrate=t}catch(i){try{t=new Be(new Le(this.originator)),await e(),this.substrate=t}catch(i){try{t=new Me(this.originator),await e(),this.substrate=t}catch(i){try{t=new Ve(this.originator),await e(),this.substrate=t}catch(t){throw new Error("No wallet available over any communication substrate. Install a BSV wallet today!")}}}}}}async createAction(t){return await this.connectToSubstrate(),await this.substrate.createAction(t,this.originator)}async signAction(t){return await this.connectToSubstrate(),await this.substrate.signAction(t,this.originator)}async abortAction(t){return await this.connectToSubstrate(),await this.substrate.abortAction(t,this.originator)}async listActions(t){return await this.connectToSubstrate(),await this.substrate.listActions(t,this.originator)}async internalizeAction(t){return await this.connectToSubstrate(),await this.substrate.internalizeAction(t,this.originator)}async listOutputs(t){return await this.connectToSubstrate(),await this.substrate.listOutputs(t,this.originator)}async relinquishOutput(t){return 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){return await this.connectToSubstrate(),await this.substrate.acquireCertificate(t,this.originator)}async listCertificates(t){return await this.connectToSubstrate(),await this.substrate.listCertificates(t,this.originator)}async proveCertificate(t){return await this.connectToSubstrate(),await this.substrate.proveCertificate(t,this.originator)}async relinquishCertificate(t){return await this.connectToSubstrate(),await this.substrate.relinquishCertificate(t,this.originator)}async discoverByIdentityKey(t){return await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(t,this.originator)}async discoverByAttributes(t){return 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 He extends Fe{keyring;decryptedFields;constructor(t,e,i,r,n,s,a,o,c){super(t,e,i,r,n,s,o),this.keyring=a,this.decryptedFields=c}static fromCertificate(t,e){return new He(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,e,t.signature)}async decryptFields(t,e,i){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 r={};for(const n in this.keyring){const{plaintext:s}=await t.decrypt({ciphertext:W(this.keyring[n],"base64"),...Fe.getCertificateFieldEncryptionDetails(n,this.serialNumber),counterparty:this.subject,privileged:e,privilegedReason:i}),a=new Ut(s).decrypt(W(this.fields[n],"base64"));r[n]=X(a)}return r}catch(t){throw new Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(t instanceof Error?t.message:t)}`)}}}class Ke{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 Ue(t,e,i="self"){const r=W(t,"base64"),n=r.slice(0,16),s=r.slice(16),{valid:a}=await e.verifyHmac({data:n,hmac:s,protocolID:[2,"server hmac"],keyID:X(n),counterparty:i});return a}async function $e(t,e="self"){const i=mt(16),{hmac:r}=await t.createHmac({protocolID:[2,"server hmac"],keyID:X(i),data:i,counterparty:e});return Y([...i,...r])}const We=async(t,e,i)=>{const r=await t.listCertificates({certifiers:e.certifiers,types:Object.keys(e.types)});return await Promise.all(r.certificates.map((async r=>{const{keyringForVerifier:n}=await t.proveCertificate({certificate:r,fieldsToReveal:e.types[r.type],verifier:i});return new He(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,n,r.signature)})))},ze=async(t,e,i)=>{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 r=>{if(r.subject!==e.identityKey)throw new Error(`The subject of one of your certificates ("${r.subject}") is not the same as the request sender ("${e.identityKey}").`);const n=new He(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,r.keyring,r.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)})))},je="0.1";class Xe{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;constructor(t,e,i,r,n){this.wallet=t,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 Ke,this.autoPersistLastSession=!1!==n}async toPeer(t,e,i){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof e&&(e=this.lastInteractedWithPeer);const r=await this.getAuthenticatedSession(e,i),n=Y(mt(32)),{signature:s}=await this.wallet.createSignature({data:t,protocolID:[2,"auth message signature"],keyID:`${n} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey}),a={version:je,messageType:"general",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:n,yourNonce:r.peerNonce,payload:t,signature:s};r.lastUpdate=Date.now(),this.sessionManager.updateSession(r);try{await this.transport.send(a)}catch(t){const e=new Error(`Failed to send message to peer ${r.peerIdentityKey??"unknown"}: ${String(t.message)}`);throw e.stack=t.stack,e}}async requestCertificates(t,e,i=1e4){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof e&&(e=this.lastInteractedWithPeer);const r=await this.getAuthenticatedSession(e,i),n=Y(mt(32)),{signature:s}=await this.wallet.createSignature({data:W(JSON.stringify(t),"utf8"),protocolID:[2,"auth message signature"],keyID:`${n} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey}),a={version:je,messageType:"certificateRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:n,initialNonce:r.sessionNonce,yourNonce:r.peerNonce,requestedCertificates:t,signature:s};r.lastUpdate=Date.now(),this.sessionManager.updateSession(r);try{await this.transport.send(a)}catch(t){throw new Error(`Failed to send certificate request message to peer ${r.peerIdentityKey??"unknown"}: ${String(t.message)}`)}}async getAuthenticatedSession(t,e){if(void 0===this.transport)throw new Error("Peer transport is not connected!");let i;if("string"==typeof t&&(i=this.sessionManager.getSession(t)),null==i||!i.isAuthenticated){const r=await this.initiateHandshake(t,e);if(i=this.sessionManager.getSession(r),null==i||!i.isAuthenticated)throw new Error("Unable to establish mutual authentication with peer!")}return i}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,e=1e4){const i=await $e(this.wallet),r=Date.now();this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:i,peerIdentityKey:t,lastUpdate:r});const n={version:je,messageType:"initialRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,initialNonce:i,requestedCertificates:this.certificatesToRequest};return await this.transport.send(n),await this.waitForInitialResponse(i,e)}async waitForInitialResponse(t,e=1e4){return await new Promise(((i,r)=>{const n=this.listenForInitialResponse(t,(t=>{clearTimeout(s),this.stopListeningForInitialResponses(n),i(t)})),s=setTimeout((()=>{this.stopListeningForInitialResponses(n),r(new Error("Initial response timed out."))}),e)}))}listenForInitialResponse(t,e){const i=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(i,{callback:e,sessionNonce:t}),i}stopListeningForInitialResponses(t){this.onInitialResponseReceivedCallbacks.delete(t)}async handleIncomingMessage(t){if("string"!=typeof t.version||t.version!==je)throw new Error(`Invalid or unsupported message auth version! Received: ${t.version}, expected: ${je}`);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 $e(this.wallet),i=Date.now();let r;this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:e,peerNonce:t.initialNonce,peerIdentityKey:t.identityKey,lastUpdate:i}),null!=t.requestedCertificates&&Array.isArray(t.requestedCertificates.certifiers)&&t.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach((e=>{e(t.identityKey,t.requestedCertificates)})):r=await We(this.wallet,t.requestedCertificates,t.identityKey));const{signature:n}=await this.wallet.createSignature({data:W(t.initialNonce+e,"base64"),protocolID:[2,"auth message signature"],keyID:`${t.initialNonce} ${e}`,counterparty:t.identityKey}),s={version:je,messageType:"initialResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,initialNonce:e,yourNonce:t.initialNonce,certificates:r,requestedCertificates:this.certificatesToRequest,signature:n};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=t.identityKey),await this.transport.send(s)}async processInitialResponse(t){if(!await Ue(t.yourNonce,this.wallet))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=W((e.sessionNonce??"")+(t.initialNonce??""),"base64"),{valid:r}=await this.wallet.verifySignature({data:i,signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${e.sessionNonce??""} ${t.initialNonce??""}`,counterparty:t.identityKey});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.lastUpdate=Date.now(),this.sessionManager.updateSession(e),this.certificatesToRequest?.certifiers?.length>0&&t.certificates?.length>0&&(await ze(this.wallet,t,this.certificatesToRequest),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 We(this.wallet,t.requestedCertificates,t.identityKey);await this.sendCertificateResponse(t.identityKey,e)}}async processCertificateRequest(t){if(!await Ue(t.yourNonce,this.wallet))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:W(JSON.stringify(t.requestedCertificates),"utf8"),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:e.peerIdentityKey});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 We(this.wallet,t.requestedCertificates,t.identityKey);await this.sendCertificateResponse(t.identityKey,e)}}async sendCertificateResponse(t,e){const i=await this.getAuthenticatedSession(t),r=Y(mt(32)),{signature:n}=await this.wallet.createSignature({data:W(JSON.stringify(e),"utf8"),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey}),s={version:je,messageType:"certificateResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,certificates:e,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(t){const e=t instanceof Error?t.message:String(t);throw new Error(`Failed to send certificate response message to peer ${i.peerIdentityKey??"unknown"}: ${e}`)}}async processCertificateResponse(t){if(!await Ue(t.yourNonce,this.wallet))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:W(JSON.stringify(t.certificates),"utf8"),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:t.identityKey});if(!i)throw new Error(`Unable to verify certificate response signature for peer: ${t.identityKey}`);await ze(this.wallet,t,t.requestedCertificates),this.onCertificatesReceivedCallbacks.forEach((e=>{e(t.identityKey,t.certificates??[])})),e.lastUpdate=Date.now(),this.sessionManager.updateSession(e)}async processGeneralMessage(t){if(!await Ue(t.yourNonce,this.wallet))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{valid:i}=await this.wallet.verifySignature({data:t.payload,signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:e.peerIdentityKey});if(!i)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??[])}))}}const Ge="undefined"!=typeof window?fetch.bind(window):fetch;class Ye{onDataCallback;fetchClient;baseUrl;constructor(t,e=Ge){this.fetchClient=e,this.baseUrl=t}async send(t){if(!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 new Promise((async(e,i)=>{try{const i=this.fetchClient(`${this.baseUrl}/.well-known/auth`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});"initialRequest"!==t.messageType&&e();const r=await i;if(!r.ok||!this.onDataCallback)throw new Error("HTTP server failed to authenticate");{const t=await r.json();this.onDataCallback(t)}"initialRequest"===t.messageType&&e()}catch(t){return void i(t)}}));{const e=this.deserializeRequestPayload(t.payload),i=`${this.baseUrl}${e.urlPostfix}`;let 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"]=$(t.signature),r.headers["x-bsv-auth-request-id"]=e.requestId,r.body){const t=r.headers;if(!t["content-type"])throw new Error("Content-Type header is required for requests with a body.");const e=t["content-type"];e.includes("application/json")||e.includes("application/x-www-form-urlencoded")||e.includes("text/plain")?r.body=X(r.body):r.body=new Uint8Array(r.body)}const n=await this.fetchClient(i,{method:r.method,headers:r.headers,body:r.body});if(500===n.status&&null==n.headers.get("x-bsv-auth-request-id")&&null==n.headers.get("x-bsv-auth-requested-certificates")){const t=await n.json();throw new Error(`HTTP ${n.status} - ${JSON.stringify(t)}`)}const s=await n.arrayBuffer(),a=new it;null!=n.headers.get("x-bsv-auth-request-id")&&a.write(W(n.headers.get("x-bsv-auth-request-id"),"base64")),a.writeVarIntNum(n.status);const o=[];n.headers.forEach(((t,e)=>{const i=e.toLowerCase();!i.startsWith("x-bsv-")&&"authorization"!==i||i.startsWith("x-bsv-auth")||o.push([i,t])})),o.sort((([t],[e])=>t.localeCompare(e))),a.writeVarIntNum(o.length);for(let t=0;t<o.length;t++){const e=W(o[t][0],"utf8");a.writeVarIntNum(e.length),a.write(e);const i=W(o[t][1],"utf8");a.writeVarIntNum(i.length),a.write(i)}if(s){const t=Array.from(new Uint8Array(s));a.writeVarIntNum(t.length),a.write(t)}else a.writeVarIntNum(-1);const c={version:n.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===n.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:n.headers.get("x-bsv-auth-identity-key"),nonce:n.headers.get("x-bsv-auth-nonce"),yourNonce:n.headers.get("x-bsv-auth-your-nonce"),requestedCertificates:JSON.parse(n.headers.get("x-bsv-auth-requested-certificates")),payload:a.toArray(),signature:W(n.headers.get("x-bsv-auth-signature"),"hex")};if(!c.version)throw new Error("HTTP server failed to authenticate");this.onDataCallback(c)}}async onData(t){this.onDataCallback=e=>{t(e)}}deserializeRequestPayload(t){const e=new rt(t),i=Y(e.read(32)),r=e.readVarIntNum();let n="GET";r>0&&(n=X(e.read(r)));const s=e.readVarIntNum();let a="";s>0&&(a=X(e.read(s)));const o=e.readVarIntNum();let c="";o>0&&(c=X(e.read(o)));const h={},d=e.readVarIntNum();if(d>0)for(let t=0;t<d;t++){const t=e.readVarIntNum(),i=e.read(t),r=X(i),n=e.readVarIntNum(),s=e.read(n),a=X(s);h[r]=a}let u;const l=e.readVarIntNum();return l>0&&(u=e.read(l)),{urlPostfix:a+c,method:n,headers:h,body:u,requestId:i}}}class Je{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;peers={};constructor(t,e,i){this.wallet=t,this.requestedCertificates=e,this.sessionManager=i||new Ke}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:n="GET",headers:s={},body:a}=e,o=new URL(t),c=o.origin;let h;if(void 0===this.peers[c]){const t=new Ye(c);h={peer:new Xe(this.wallet,t,this.requestedCertificates,this.sessionManager),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 We(this.wallet,e,t);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 d=mt(32),u=Y(d),l=await this.serializeRequest(n,s,a,o,d);this.callbacks[u]={resolve:i,reject:r};const f=h.peer.listenForGeneralMessages(((t,e)=>{const i=new rt(e);if(Y(i.read(32))!==u)return;h.peer.stopListeningForGeneralMessages(f),this.peers[c].identityKey=t,this.peers[c].supportsMutualAuth=!0;const r=i.readVarIntNum(),n={},s=i.readVarIntNum();if(s>0)for(let t=0;t<s;t++){const t=i.readVarIntNum(),e=i.read(t),r=X(e),s=i.readVarIntNum(),a=i.read(s),o=X(a);n[r]=o}let a;n["x-bsv-auth-identity-key"]=t;const o=i.readVarIntNum();o>0&&(a=i.read(o));const d=new Response(a?new Uint8Array(a):null,{status:r,statusText:`${r}`,headers:new Headers(n)});this.callbacks[u].resolve(d),delete this.callbacks[u]}));h.pendingCertificateRequests.length>0&&await new Promise((t=>{setInterval((()=>{0===h.pendingCertificateRequests.length&&t()}),100)})),await h.peer.toPeer(l.toArray(),h.identityKey).catch((async n=>{if(n.message.includes("Session not found for nonce")){delete this.peers[c],e.retryCounter??=3;const r=await this.fetch(t,e);i(r)}else if(n.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(n)}))}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 Ye(i);r={peer:new Xe(this.wallet,t,this.requestedCertificates,this.sessionManager)},this.peers[i]=r}return await new Promise((async(t,i)=>{const n=r.peer.listenForCertificatesReceived(((e,i)=>{r.peer.stopListeningForCertificatesReceived(n),this.certificatesReceived.push(...i),t(i)}));try{await r.peer.requestCertificates(e,r.identityKey)}catch(t){r.peer.stopListeningForCertificatesReceived(n),i(t)}}))}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(t,e,i,r,n){const s=new it;if(s.write(n),s.writeVarIntNum(t.length),s.write(W(t)),r.pathname.length>0){const t=W(r.pathname);s.writeVarIntNum(t.length),s.write(t)}else s.writeVarIntNum(-1);if(r.search.length>0){const t=W(r.search);s.writeVarIntNum(t.length),s.write(t)}else s.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))),s.writeVarIntNum(a.length);for(let t=0;t<a.length;t++){const e=W(a[t][0],"utf8");s.writeVarIntNum(e.length),s.write(e);const i=W(a[t][1],"utf8");s.writeVarIntNum(i.length),s.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);s.writeVarIntNum(t.length),s.write(t)}else s.writeVarIntNum(-1);return s}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 n=i.headers.get("x-bsv-payment-satoshis-required");if(!n)throw new Error("Missing x-bsv-payment-satoshis-required response header.");const s=parseInt(n);if(isNaN(s)||s<=0)throw new Error("Invalid x-bsv-payment-satoshis-required response header value.");const a=i.headers.get("x-bsv-auth-identity-key");if(!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.");const c=await $e(this.wallet),{publicKey:h}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${o} ${c}`,counterparty:a}),d=(new ne).lock(bt.fromString(h).toAddress()).toHex(),{tx:u}=await this.wallet.createAction({description:`Payment for request to ${new URL(t).origin}`,outputs:[{satoshis:s,lockingScript:d,customInstructions:JSON.stringify({derivationPrefix:o,derivationSuffix:c,payee:a}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}});return e.headers=e.headers||{},e.headers["x-bsv-payment"]=JSON.stringify({derivationPrefix:o,derivationSuffix:c,transaction:Y(u)}),e.retryCounter??=3,this.fetch(t,e)}async normalizeBodyToNumberArray(t){if(null==t)return[];if("object"==typeof t)return W(JSON.stringify(t,"utf8"));if(Array.isArray(t)&&t.every((t=>"number"==typeof t)))return t;if("string"==typeof t)return W(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 W(i,"utf8")}if(t instanceof URLSearchParams)return W(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 Ze{pushDrop;static decode(t){const e=ae.decode(t);if(e.fields.length<4)throw new Error("Invalid SHIP/SLAP advertisement!");const i=X(e.fields[0]);if("SHIP"!==i&&"SLAP"!==i)throw new Error("Invalid protocol type!");return{protocol:i,identityKey:$(e.fields[1]),domain:X(e.fields[2]),topicOrService:X(e.fields[3])}}constructor(t){this.pushDrop=new ae(t)}async lock(t,e,i){const{publicKey:r}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([W(t,"utf8"),W(r,"hex"),W(e,"utf8"),W(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 Qe=["https://users.bapp.dev"],ti=["https://testnet-users.bapp.dev"];class ei{fetchClient;allowHTTP;constructor(t=fetch,e=!1){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=new Promise(((t,e)=>setTimeout((()=>e(new Error("Request timed out"))),i))),n=fetch(`${t}/lookup`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:e.service,query:e.query})}),s=await Promise.race([n,r]);if(s.ok)return await s.json();throw new Error("Failed to facilitate lookup")}}class ii{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;constructor(t={}){this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new ei(void 0,"local"===this.networkPreset),this.slapTrackers=t.slapTrackers??("mainnet"===this.networkPreset?Qe:ti),this.hostOverrides=t.hostOverrides??{},this.additionalHosts=t.additionalHosts??{}}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.findCompetentHosts(t.service),this.additionalHosts[t.service]?.length>0&&(i=[...i,...this.additionalHosts[t.service]]),i.length<1)throw new Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${t.service}`);const r=(await Promise.allSettled(i.map((async i=>await this.facilitator.lookup(i,t,e))))).filter((t=>"fulfilled"===t.status)).map((t=>t.value));if(0===r.length)throw new Error("No successful responses from any hosts");const n=new Map;for(const t of r)if("output-list"===t.type)try{for(const e of t.outputs)try{const t=`${Se.fromBEEF(e.beef).id("hex")}.${e.outputIndex}`;n.set(t,e)}catch{continue}}catch(t){}return{type:"output-list",outputs:Array.from(n.values())}}async findCompetentHosts(t){const e={service:"ls_slap",query:{service:t}},i=await Promise.allSettled(this.slapTrackers.map((async t=>await this.facilitator.lookup(t,e,5e3)))),r=new Set;for(const e of i)if("fulfilled"===e.status){const i=e.value;if("output-list"!==i.type)continue;for(const e of i.outputs)try{const i=Se.fromBEEF(e.beef).outputs[e.outputIndex].lockingScript,n=Ze.decode(i);if(n.topicOrService!==t||"SLAP"!==n.protocol)continue;r.add(n.domain)}catch{continue}}return[...r]}}class ri{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 it;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 n=await fetch(`${t}/submit`,{method:"POST",headers:i,body:r});if(n.ok)return await n.json();throw new Error("Failed to facilitate broadcast")}}class ni{topics;facilitator;resolver;requireAcknowledgmentFromAllHostsForTopics;requireAcknowledgmentFromAnyHostForTopics;requireAcknowledgmentFromSpecificHostsForTopics;networkPreset;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 ri(void 0,"local"===this.networkPreset),this.resolver=e.resolver??new ii({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=e.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=e.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=e.requireAcknowledgmentFromSpecificHostsForTopics??{}}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 n=Object.entries(r).map((async([t,r])=>{try{const n=await this.facilitator.send(t,{beef:e,offChainValues:i,topics:[...r]});if(null==n||0===Object.keys(n).length)throw new Error("Steak has no topics.");return{host:t,success:!0,steak:n}}catch(e){return console.error(e),{host:t,success:!1,error:e}}})),s=(await Promise.all(n)).filter((t=>t.success));if(0===s.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 s){const e=t.host,i=t.steak,r=new Set;for(const[t,e]of Object.entries(i)){const i=e.outputsToAdmit,n=e.coinsToRetain,s=e.coinsRemoved;(i?.length>0||n?.length>0||s?.length>0)&&r.add(t)}a[e]=r}let o,c,h,d;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,d="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(h=this.topics,d="any"):Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?(h=this.requireAcknowledgmentFromAnyHostForTopics,d="all"):(h=[],d="all"),h.length>0&&!this.checkAcknowledgmentFromAnyHost(a,h,d)?{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 ${s.length} Overlay Services ${1===s.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 n,s;if("all"===r||"any"===r)s=r,n=this.topics;else{if(!Array.isArray(r))continue;n=r,s="all"}if("all"===s){for(const t of n)if(!e.has(t))return!1}else if("any"===s){let t=!1;for(const i of n)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={},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=Se.fromBEEF(i.beef).outputs[i.outputIndex].lockingScript,r=Ze.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 si=Object.create(null);si.open="0",si.close="1",si.ping="2",si.pong="3",si.message="4",si.upgrade="5",si.noop="6";const ai=Object.create(null);Object.keys(si).forEach((t=>{ai[si[t]]=t}));const oi={type:"error",data:"parser error"},ci="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),hi="function"==typeof ArrayBuffer,di=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,ui=({type:t,data:e},i,r)=>ci&&e instanceof Blob?i?r(e):li(e,r):hi&&(e instanceof ArrayBuffer||di(e))?i?r(e):li(new Blob([e]),r):r(si[t]+(e||"")),li=(t,e)=>{const i=new FileReader;return i.onload=function(){const t=i.result.split(",")[1];e("b"+(t||""))},i.readAsDataURL(t)};function fi(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let pi;const bi="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)bi["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const gi="function"==typeof ArrayBuffer,yi=(t,e)=>{if("string"!=typeof t)return{type:"message",data:wi(t,e)};const i=t.charAt(0);return"b"===i?{type:"message",data:mi(t.substring(1),e)}:ai[i]?t.length>1?{type:ai[i],data:t.substring(1)}:{type:ai[i]}:oi},mi=(t,e)=>{if(gi){const i=(t=>{let e,i,r,n,s,a=.75*t.length,o=t.length,c=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);const h=new ArrayBuffer(a),d=new Uint8Array(h);for(e=0;e<o;e+=4)i=bi[t.charCodeAt(e)],r=bi[t.charCodeAt(e+1)],n=bi[t.charCodeAt(e+2)],s=bi[t.charCodeAt(e+3)],d[c++]=i<<2|r>>4,d[c++]=(15&r)<<4|n>>2,d[c++]=(3&n)<<6|63&s;return h})(t);return wi(i,e)}return{base64:!0,data:t}},wi=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,Ii=String.fromCharCode(30);let vi;function ki(t){return t.reduce(((t,e)=>t+e.length),0)}function Si(t,e){if(t[0].length===e)return t.shift();const i=new Uint8Array(e);let r=0;for(let n=0;n<e;n++)i[n]=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 _i(t){if(t)return function(t){for(var e in _i.prototype)t[e]=_i.prototype[e];return t}(t)}_i.prototype.on=_i.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},_i.prototype.once=function(t,e){function i(){this.off(t,i),e.apply(this,arguments)}return i.fn=e,this.on(t,i),this},_i.prototype.off=_i.prototype.removeListener=_i.prototype.removeAllListeners=_i.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 n=0;n<r.length;n++)if((i=r[n])===e||i.fn===e){r.splice(n,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},_i.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 n=(i=i.slice(0)).length;r<n;++r)i[r].apply(this,e)}return this},_i.prototype.emitReserved=_i.prototype.emit,_i.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},_i.prototype.hasListeners=function(t){return!!this.listeners(t).length};const Ei="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),Pi="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Oi(t,...e){return e.reduce(((e,i)=>(t.hasOwnProperty(i)&&(e[i]=t[i]),e)),{})}const Ni=Pi.setTimeout,Ai=Pi.clearTimeout;function xi(t,e){e.useNativeTimers?(t.setTimeoutFn=Ni.bind(Pi),t.clearTimeoutFn=Ai.bind(Pi)):(t.setTimeoutFn=Pi.setTimeout.bind(Pi),t.clearTimeoutFn=Pi.clearTimeout.bind(Pi))}function Ti(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Ci extends Error{constructor(t,e,i){super(t),this.description=e,this.context=i,this.type="TransportError"}}class Fi extends _i{constructor(t){super(),this.writable=!1,xi(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 Ci(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=yi(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 Ri extends Fi{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(Ii),r=[];for(let t=0;t<i.length;t++){const n=yi(i[t],e);if(r.push(n),"error"===n.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 n=0;t.forEach(((t,s)=>{ui(t,!1,(t=>{r[s]=t,++n===i&&e(r.join(Ii))}))}))})(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]=Ti()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let Bi=!1;try{Bi="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const Li=Bi;function Di(){}class Mi extends Ri{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 Vi extends _i{constructor(t,e,i){super(),this.createRequest=t,xi(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=Oi(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=Vi.requestsCount++,Vi.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=Di,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Vi.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 qi(){for(let t in Vi.requests)Vi.requests.hasOwnProperty(t)&&Vi.requests[t].abort()}Vi.requestsCount=0,Vi.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",qi):"function"==typeof addEventListener&&addEventListener("onpagehide"in Pi?"pagehide":"unload",qi,!1));const Hi=function(){const t=Ki({xdomain:!1});return t&&null!==t.responseType}();function Ki(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||Li))return new XMLHttpRequest}catch(t){}if(!e)try{return new(Pi[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const Ui="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class $i extends Fi{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,i=Ui?{}:Oi(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;ui(i,this.supportsBinary,(t=>{try{this.doWrite(i,t)}catch(t){}r&&Ei((()=>{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]=Ti()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const Wi=Pi.WebSocket||Pi.MozWebSocket,zi={websocket:class extends $i{createSocket(t,e,i){return Ui?new Wi(t,e,i):e?new Wi(t,e):new Wi(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends Fi{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){vi||(vi=new TextDecoder);const i=[];let r=0,n=-1,s=!1;return new TransformStream({transform(a,o){for(i.push(a);;){if(0===r){if(ki(i)<1)break;const t=Si(i,1);s=!(128&~t[0]),n=127&t[0],r=n<126?3:126===n?1:2}else if(1===r){if(ki(i)<2)break;const t=Si(i,2);n=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),r=3}else if(2===r){if(ki(i)<8)break;const t=Si(i,8),e=new DataView(t.buffer,t.byteOffset,t.length),s=e.getUint32(0);if(s>Math.pow(2,21)-1){o.enqueue(oi);break}n=s*Math.pow(2,32)+e.getUint32(4),r=3}else{if(ki(i)<n)break;const t=Si(i,n);o.enqueue(yi(s?t:vi.decode(t),e)),r=0}if(0===n||n>t){o.enqueue(oi);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=t.readable.pipeThrough(e).getReader(),r=new TransformStream({transform(t,e){!function(t,e){ci&&t.data instanceof Blob?t.data.arrayBuffer().then(fi).then(e):hi&&(t.data instanceof ArrayBuffer||di(t.data))?e(fi(t.data)):ui(t,!1,(t=>{pi||(pi=new TextEncoder),e(pi.encode(t))}))}(t,(i=>{const r=i.length;let n;if(r<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,r);else if(r<65536){n=new Uint8Array(3);const t=new DataView(n.buffer);t.setUint8(0,126),t.setUint16(1,r)}else{n=new Uint8Array(9);const t=new DataView(n.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(r))}t.data&&"string"!=typeof t.data&&(n[0]|=128),e.enqueue(n),e.enqueue(i)}))}});r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const n=()=>{i.read().then((({done:t,value:e})=>{t||(this.onPacket(e),n())})).catch((t=>{}))};n();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this._writer.write(s).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&&Ei((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends Mi{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Hi&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Vi(Ki,this.uri(),t)}}},ji=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Xi=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Gi(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 n=ji.exec(t||""),s={},a=14;for(;a--;)s[Xi[a]]=n[a]||"";return-1!=i&&-1!=r&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.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,s.path),s.queryKey=function(t,e){const i={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,r){e&&(i[e]=r)})),i}(0,s.query),s}const Yi="function"==typeof addEventListener&&"function"==typeof removeEventListener,Ji=[];Yi&&addEventListener("offline",(()=>{Ji.forEach((t=>t()))}),!1);class Zi extends _i{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=Gi(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=Gi(e.host).host);xi(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)),Yi&&(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"})},Ji.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&&Zi.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",Zi.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 i=0;i<this.writeBuffer.length;i++){const r=this.writeBuffer[i].data;if(r&&(t+="string"==typeof(e=r)?function(t){let e=0,i=0;for(let r=0,n=t.length;r<n;r++)e=t.charCodeAt(r),e<128?i+=1:e<2048?i+=2:e<55296||e>=57344?i+=3:(r++,i+=4);return i}(e):Math.ceil(1.33*(e.byteLength||e.size))),i>0&&t>this._maxPayload)return this.writeBuffer.slice(0,i);t+=2}var e;return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Ei((()=>{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 n={type:t,data:e,options:i};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),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(Zi.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(),Yi&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=Ji.indexOf(this._offlineEventListener);-1!==t&&Ji.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}Zi.protocol=4;class Qi extends Zi{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;Zi.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;Zi.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 n(){i||(i=!0,h(),e.close(),e=null)}const s=t=>{const i=new Error("probe error: "+t);i.transport=e.name,n(),this.emitReserved("upgradeError",i)};function a(){s("transport closed")}function o(){s("socket closed")}function c(t){e&&t.name!==e.name&&n()}const h=()=>{e.removeListener("open",r),e.removeListener("error",s),e.removeListener("close",a),this.off("close",o),this.off("upgrading",c)};e.once("open",r),e.once("error",s),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 tr extends Qi{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=>zi[t])).filter((t=>!!t))),super(t,i)}}const er="function"==typeof ArrayBuffer,ir=Object.prototype.toString,rr="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ir.call(Blob),nr="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ir.call(File);function sr(t){return er&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||rr&&t instanceof Blob||nr&&t instanceof File}function ar(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,i=t.length;e<i;e++)if(ar(t[e]))return!0;return!1}if(sr(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return ar(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&ar(t[e]))return!0;return!1}function or(t){const e=[],i=t.data,r=t;return r.data=cr(i,e),r.attachments=e.length,{packet:r,buffers:e}}function cr(t,e){if(!t)return t;if(sr(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]=cr(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]=cr(t[r],e));return i}return t}function hr(t,e){return t.data=dr(t.data,e),delete t.attachments,t}function dr(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]=dr(t[i],e);else if("object"==typeof t)for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=dr(t[i],e));return t}const ur=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],lr=5;var fr;!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"}(fr||(fr={}));class pr{constructor(t){this.replacer=t}encode(t){return t.type!==fr.EVENT&&t.type!==fr.ACK||!ar(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===fr.EVENT?fr.BINARY_EVENT:fr.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==fr.BINARY_EVENT&&t.type!==fr.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=or(t),i=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(i),r}}function br(t){return"[object Object]"===Object.prototype.toString.call(t)}class gr extends _i{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===fr.BINARY_EVENT;i||e.type===fr.BINARY_ACK?(e.type=i?fr.EVENT:fr.ACK,this.reconstructor=new yr(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!sr(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===fr[i.type])throw new Error("unknown packet type "+i.type);if(i.type===fr.BINARY_EVENT||i.type===fr.BINARY_ACK){const r=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const n=t.substring(r,e);if(n!=Number(n)||"-"!==t.charAt(e))throw new Error("Illegal attachments");i.attachments=Number(n)}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(!gr.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 fr.CONNECT:return br(e);case fr.DISCONNECT:return void 0===e;case fr.CONNECT_ERROR:return"string"==typeof e||br(e);case fr.EVENT:case fr.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===ur.indexOf(e[0]));case fr.ACK:case fr.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class yr{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=hr(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function mr(t,e,i){return t.on(e,i),function(){t.off(e,i)}}const wr=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Ir extends _i{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=[mr(t,"open",this.onopen.bind(this)),mr(t,"packet",this.onpacket.bind(this)),mr(t,"error",this.onerror.bind(this)),mr(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,n;if(wr.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 s={type:fr.EVENT,data:e,options:{}};if(s.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,i=e.pop();this._registerAckCallback(t,i),s.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===(n=this.io.engine)||void 0===n?void 0:n._hasPingExpired());return this.flags.volatile&&!a||(o?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),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 n=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),s=(...t)=>{this.io.clearTimeoutFn(n),e.apply(this,t)};s.withError=!0,this.acks[t]=s}emitWithAck(t,...e){return new Promise(((i,r)=>{const n=(t,e)=>t?r(t):i(e);n.withError=!0,e.push(n),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:fr.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 fr.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 fr.EVENT:case fr.BINARY_EVENT:this.onevent(t);break;case fr.ACK:case fr.BINARY_ACK:this.onack(t);break;case fr.DISCONNECT:this.ondisconnect();break;case fr.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:fr.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:fr.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 vr(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}vr.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)},vr.prototype.reset=function(){this.attempts=0},vr.prototype.setMin=function(t){this.ms=t},vr.prototype.setMax=function(t){this.max=t},vr.prototype.setJitter=function(t){this.jitter=t};class kr extends _i{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,xi(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 vr({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const n=e.parser||i;this.encoder=new n.Encoder,this.decoder=new n.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 tr(this.uri,this.opts);const e=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const r=mr(e,"open",(function(){i.onopen(),t&&t()})),n=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},s=mr(e,"error",n);if(!1!==this._timeout){const t=this._timeout,i=this.setTimeoutFn((()=>{r(),n(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(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(mr(t,"ping",this.onping.bind(this)),mr(t,"data",this.ondata.bind(this)),mr(t,"error",this.onerror.bind(this)),mr(t,"close",this.onclose.bind(this)),mr(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){Ei((()=>{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 Ir(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 Sr={};function _r(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=Gi(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 n=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+n+":"+r.port+e,r.href=r.protocol+"://"+n+(i&&i.port===r.port?"":":"+r.port),r}(t,(e=e||{}).path||"/socket.io"),r=i.source,n=i.id,s=i.path,a=Sr[n]&&s in Sr[n].nsps;let o;return e.forceNew||e["force new connection"]||!1===e.multiplex||a?o=new kr(r,e):(Sr[n]||(Sr[n]=new kr(r,e)),o=Sr[n]),i.query&&!e.query&&(e.query=i.queryKey),o.socket(i.path,e)}Object.assign(_r,{Manager:kr,Socket:Ir,io:_r,connect:_r});class Er{socket;onDataCallback;constructor(t){this.socket=t,this.socket.on("authMessage",(async t=>{this.onDataCallback&&await this.onDataCallback(t)}))}async send(t){this.socket.emit("authMessage",t)}async onData(t){this.onDataCallback=t}}class Pr{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 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(i)for(const t of i)t(e)}encodeEventPayload(t,e){const i={eventName:t,data:e};return W(JSON.stringify(i),"utf8")}decodeEventPayload(t){try{const e=X(t);return JSON.parse(e)}catch{return{eventName:"_unknown",data:void 0}}}}class Or{static isEnabled=!1;static enable(){this.isEnabled=!0}static disable(){this.isEnabled=!1}static log(...t){this.isEnabled&&console.log(...t)}static warn(...t){this.isEnabled&&console.warn(...t)}static error(...t){console.error(...t)}}class Nr{host;authFetch;walletClient;socket;myIdentityKey;joinedRooms=new Set;lookupResolver;networkPreset;initialized=!1;constructor(t={}){const{host:e,walletClient:i,enableLogging:r=!1,networkPreset:n="mainnet"}=t,s="testnet"===this.networkPreset?"https://staging-messagebox.babbage.systems":"https://messagebox.babbage.systems";this.host=e?.trim()??s,this.walletClient=i??new qe,this.authFetch=new Je(this.walletClient),this.networkPreset=n,this.lookupResolver=new ii({networkPreset:n}),r&&Or.enable()}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){Or.log("[MB CLIENT] Anointing host:",e);const{txid:t}=await this.anointHost(e);if(null==t||""===t.trim())throw new Error("Failed to anoint host: No transaction ID returned")}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;Or.log("[MB CLIENT] Fetching identity key...");try{const t=await this.walletClient.getPublicKey({identityKey:!0});return this.myIdentityKey=t.publicKey,Or.log(`[MB CLIENT] Identity key fetched: ${this.myIdentityKey}`),this.myIdentityKey}catch(t){throw Or.error("[MB CLIENT ERROR] Failed to fetch identity key:",t),new Error("Identity key retrieval failed")}}get testSocket(){return this.socket}async initializeConnection(){if(await this.assertInitialized(),Or.log("[MB CLIENT] initializeConnection() STARTED"),null==this.myIdentityKey||""===this.myIdentityKey.trim()){Or.log("[MB CLIENT] Fetching identity key...");try{const t=await this.walletClient.getPublicKey({identityKey:!0});this.myIdentityKey=t.publicKey,Or.log(`[MB CLIENT] Identity key fetched successfully: ${this.myIdentityKey}`)}catch(t){throw Or.error("[MB CLIENT ERROR] Failed to fetch identity key:",t),new Error("Identity key retrieval failed")}}if(null==this.myIdentityKey||""===this.myIdentityKey.trim())throw Or.error("[MB CLIENT ERROR] Identity key is still missing after retrieval!"),new Error("Identity key is missing");if(Or.log("[MB CLIENT] Setting up WebSocket connection..."),null==this.socket){if("string"!=typeof this.host||""===this.host.trim())throw new Error("Cannot initialize WebSocket: Host is not set");this.socket=function(t,e){const i=_r(t,e.managerOptions),r=new Er(i),n=new Xe(e.wallet,r,e.requestedCertificates,e.sessionManager);return new Pr(i,n)}(this.host,{wallet:this.walletClient});let t=!1,e=!1;this.socket.on("connect",(()=>{Or.log("[MB CLIENT] Connected to WebSocket."),t||(Or.log("[MB CLIENT] Sending authentication data:",this.myIdentityKey),null==this.myIdentityKey||""===this.myIdentityKey.trim()?Or.error("[MB CLIENT ERROR] Cannot send authentication: Identity key is missing!"):(this.socket?.emit("authenticated",{identityKey:this.myIdentityKey}),t=!0))})),this.socket.on("authenticationSuccess",(t=>{Or.log(`[MB CLIENT] WebSocket authentication successful: ${JSON.stringify(t)}`),e=!0})),this.socket.on("authenticationFailed",(t=>{Or.error(`[MB CLIENT ERROR] WebSocket authentication failed: ${JSON.stringify(t)}`),e=!1})),this.socket.on("disconnect",(()=>{Or.log("[MB CLIENT] Disconnected from MessageBox server"),this.socket=void 0,t=!1,e=!1})),this.socket.on("error",(t=>{Or.error("[MB CLIENT ERROR] WebSocket error:",t)})),await new Promise(((t,i)=>{setTimeout((()=>{e?(Or.log("[MB CLIENT] WebSocket fully authenticated and ready!"),t()):i(new Error("[MB CLIENT ERROR] WebSocket authentication timed out!"))}),5e3)}))}}async resolveHostForRecipient(t){const e=await this.queryAdvertisements(t);return 0===e.length?(Or.warn(`[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 n=await this.lookupResolver.query({service:"ls_messagebox",query:r});if("output-list"!==n.type)throw new Error(`Unexpected result type: ${n.type}`);for(const t of n.outputs)try{const e=Se.fromBEEF(t.beef),r=e.outputs[t.outputIndex].lockingScript,n=ae.decode(r),[,s]=n.fields;if(null==s||0===s.length)throw new Error("Empty host field");i.push({host:X(s),txid:e.id("hex"),outputIndex:t.outputIndex,lockingScript:r,beef:t.beef})}catch{}}catch(t){Or.error("[MB CLIENT ERROR] _queryAdvertisements failed:",t)}return i}async joinRoom(t){if(await this.assertInitialized(),Or.log(`[MB CLIENT] Attempting to join WebSocket room: ${t}`),null==this.socket&&(Or.log("[MB CLIENT] No WebSocket connection. Initializing..."),await this.initializeConnection()),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw new Error("[MB CLIENT ERROR] Identity key is not defined");const e=`${this.myIdentityKey??""}-${t}`;if(this.joinedRooms.has(e))Or.log(`[MB CLIENT] Already joined WebSocket room: ${e}`);else try{Or.log(`[MB CLIENT] Joining WebSocket room: ${e}`),await(this.socket?.emit("joinRoom",e)),this.joinedRooms.add(e),Or.log(`[MB CLIENT] Successfully joined room: ${e}`)}catch(t){Or.error(`[MB CLIENT ERROR] Failed to join WebSocket room: ${e}`,t)}}async listenForLiveMessages({onMessage:t,messageBox:e}){if(await this.assertInitialized(),Or.log(`[MB CLIENT] Setting up listener for WebSocket room: ${e}`),await this.joinRoom(e),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw new Error("[MB CLIENT ERROR] Identity key is missing. Cannot construct room ID.");const i=`${this.myIdentityKey}-${e}`;Or.log(`[MB CLIENT] Listening for messages in room: ${i}`),this.socket?.on(`sendMessage-${i}`,(e=>{(async()=>{Or.log(`[MB CLIENT] Received message in room ${i}:`,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){Or.log(`[MB CLIENT] Decrypting message from ${String(e.sender)}...`);const i=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:e.sender,ciphertext:W(t.encryptedMessage,"base64")});e.body=X(i.plaintext)}else Or.log("[MB CLIENT] Message is not encrypted."),e.body="string"==typeof t?t:(()=>{try{return JSON.stringify(t)}catch{return"[Error: Unstringifiable message]"}})()}catch(t){Or.error("[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:n}){if(await this.assertInitialized(),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),null==this.socket||!this.socket.connected){Or.warn("[MB CLIENT WARNING] WebSocket not connected, falling back to HTTP");const r=await this.resolveHostForRecipient(t);return await this.sendMessage({recipient:t,messageBox:e,body:i},r)}let s;try{const e=await this.walletClient.createHmac({data:Array.from((new TextEncoder).encode(JSON.stringify(i))),protocolID:[1,"messagebox"],keyID:"1",counterparty:t});s=r??Array.from(e.hmac).map((t=>t.toString(16).padStart(2,"0"))).join("")}catch(t){throw Or.error("[MB CLIENT ERROR] Failed to generate HMAC:",t),new Error("Failed to generate message identifier.")}const a=`${t}-${e}`;let o;if(Or.log(`[MB CLIENT] Sending WebSocket message to room: ${a}`),!0===n)o="string"==typeof i?i:JSON.stringify(i);else{const e=await this.walletClient.encrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t,plaintext:W("string"==typeof i?i:JSON.stringify(i),"utf8")});o=JSON.stringify({encryptedMessage:Y(e.ciphertext)})}return await new Promise(((r,c)=>{const h=`sendMessageAck-${a}`;let d=!1;const u=a=>{if(d)return;d=!0;const o=this.socket;if("function"==typeof o?.off&&o.off(h,u),Or.log("[MB CLIENT] Received WebSocket acknowledgment:",a),null==a||"success"!==a.status){Or.warn("[MB CLIENT] WebSocket message failed or returned unexpected response. Falling back to HTTP.");const a={recipient:t,messageBox:e,body:i,messageId:s,skipEncryption:n};this.resolveHostForRecipient(t).then((async t=>await this.sendMessage(a,t))).then(r).catch(c)}else Or.log("[MB CLIENT] Message sent successfully via WebSocket:",a),r(a)};this.socket?.on(h,u),this.socket?.emit("sendMessage",{roomId:a,message:{messageId:s,recipient:t,body:o}}),setTimeout((()=>{if(!d){d=!0;const a=this.socket;"function"==typeof a?.off&&a.off(h,u),Or.warn("[CLIENT] WebSocket acknowledgment timed out, falling back to HTTP");const o={recipient:t,messageBox:e,body:i,messageId:s,skipEncryption:n};this.resolveHostForRecipient(t).then((async t=>await this.sendMessage(o,t))).then(r).catch(c)}}),1e4)}))}async leaveRoom(t){if(await this.assertInitialized(),null==this.socket)return void Or.warn("[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}`;Or.log(`[MB CLIENT] Leaving WebSocket room: ${e}`),this.socket.emit("leaveRoom",e),this.joinedRooms.delete(e)}async disconnectWebSocket(){await this.assertInitialized(),null!=this.socket?(Or.log("[MB CLIENT] Closing WebSocket connection..."),this.socket.disconnect(),this.socket=void 0):Or.log("[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;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});i=t.messageId??Array.from(e.hmac).map((t=>t.toString(16).padStart(2,"0"))).join("")}catch(t){throw Or.error("[MB CLIENT ERROR] Failed to generate HMAC:",t),new Error("Failed to generate message identifier.")}if(!0===t.skipEncryption)r="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:W("string"==typeof t.body?t.body:JSON.stringify(t.body),"utf8")});r=JSON.stringify({encryptedMessage:Y(e.ciphertext)})}const n={message:{...t,messageId:i,body:r}};try{const r=e??await this.resolveHostForRecipient(t.recipient);if(Or.log("[MB CLIENT] Sending HTTP request to:",`${r}/sendMessage`),Or.log("[MB CLIENT] Request Body:",JSON.stringify(n,null,2)),null==this.myIdentityKey||""===this.myIdentityKey)try{const t=await this.walletClient.getPublicKey({identityKey:!0});this.myIdentityKey=t.publicKey,Or.log(`[MB CLIENT] Fetched identity key before sending request: ${this.myIdentityKey}`)}catch(t){throw Or.error("[MB CLIENT ERROR] Failed to fetch identity key:",t),new Error("Identity key retrieval failed")}const s=await this.authFetch.fetch(`${r}/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(Or.log("[MB CLIENT] Raw Response Body:",a),!s.ok)throw Or.error(`[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 Or.error(`[MB CLIENT ERROR] Server returned an error: ${String(a.description)}`),new Error(a.description??"Unknown error from server.");return Or.log("[MB CLIENT] Message successfully sent."),{...a,messageId:i}}catch(t){Or.error("[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 anointHost(t){Or.log("[MB CLIENT] Starting anointHost...");try{if(!t.startsWith("http"))throw new Error("Invalid host URL");const e=await this.getIdentityKey();Or.log("[MB CLIENT] Fields - Identity:",e,"Host:",t);const i=[W(e,"hex"),W(t,"utf8")],r=new ae(this.walletClient);Or.log("Fields:",i.map((t=>$(t)))),Or.log("ProtocolID:",[1,"messagebox advertisement"]),Or.log("KeyID:","1"),Or.log("SignAs:","self"),Or.log("anyoneCanSpend:",!1),Or.log("forSelf:",!0);const n=await r.lock(i,[1,"messagebox advertisement"],"1","anyone",!0);Or.log("[MB CLIENT] PushDrop script:",n.toASM());const{tx:s,txid:a}=await this.walletClient.createAction({description:"Anoint host for overlay routing",outputs:[{basket:"overlay advertisements",lockingScript:n.toHex(),satoshis:1,outputDescription:"Overlay advertisement output"}],options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1}});if(Or.log("[MB CLIENT] Transaction created:",a),void 0!==s){const t=new ni(["tm_messagebox"],{networkPreset:this.networkPreset}),e=await t.broadcast(Se.fromAtomicBEEF(s));if(Or.log("[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 Or.error("[MB CLIENT ERROR] anointHost threw:",t),t}}async revokeHostAdvertisement(t){Or.log("[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"}]});if(void 0===i)throw new Error("Failed to create signable transaction.");const r=Se.fromBEEF(i.tx),n=new ae(this.walletClient),s=await n.unlock([1,"messagebox advertisement"],"1","anyone","all",!1,t.outputIndex,t.lockingScript),a=await s.sign(r,t.outputIndex),{tx:o}=await this.walletClient.signAction({reference:i.reference,spends:{[t.outputIndex]:{unlockingScript:a.toHex()}},options:{acceptDelayedBroadcast:!1}});if(void 0===o)throw new Error("Failed to finalize the transaction signature.");const c=new ni(["tm_messagebox"],{networkPreset:this.networkPreset}),h=await c.broadcast(Se.fromAtomicBEEF(o));if(Or.log("[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 Or.error("[MB CLIENT ERROR] revokeHost threw:",t),t}}async listMessages({messageBox:t,host:e}){if(await this.assertInitialized(),""===t.trim())throw new Error("MessageBox cannot be empty");let i=null!=e?[e]:[];if(0===i.length){const t=await this.queryAdvertisements(await this.getIdentityKey());i=Array.from(new Set([this.host,...t.map((t=>t.host))]))}const r=await Promise.allSettled(i.map((async e=>{try{Or.log(`[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 Or.log(`[MB CLIENT DEBUG] listMessages failed for ${e}:`,t),t}}))),n=[],s=[];for(const t of r)"fulfilled"===t.status?n.push(t.value):s.push(t.reason);if(0===n.length)throw new Error("Failed to retrieve messages from any host");const a=new Map;for(const t of n)for(const e of t)a.has(e.messageId)||a.set(e.messageId,e);if(0===a.size)return[];const o=t=>{try{return JSON.parse(t)}catch{return t}},c=Array.from(a.values());for(const t of c)try{const e="string"==typeof t.body?o(t.body):t.body;if(null!=e&&"object"==typeof e&&"string"==typeof e.encryptedMessage){Or.log(`[MB CLIENT] Decrypting message from ${String(t.sender)}…`);const i=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t.sender,ciphertext:W(e.encryptedMessage,"base64")}),r=X(i.plaintext);t.body=o(r)}else t.body=e}catch(e){Or.error("[MB CLIENT ERROR] Failed to parse or decrypt message in list:",e),t.body="[Error: Failed to decrypt or parse message]"}return c.sort(((t,e)=>Number(e.timestamp??0)-Number(t.timestamp??0))),c}async acknowledgeMessage({messageIds:t,host:e}){if(await this.assertInitialized(),!Array.isArray(t)||0===t.length)throw new Error("Message IDs array cannot be empty");Or.log(`[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);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 Or.log(`[MB CLIENT] Acknowledged on ${e}`),r.status}catch(t){return Or.warn(`[MB CLIENT WARN] acknowledgeMessage failed for ${e}:`,t),null}}))),n=r.filter((t=>"fulfilled"===t.status)),s=n.find((t=>null!=t.value))?.value;if(null!=s)return s;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("; ")}`)}}function Ar(t){try{return"string"==typeof t?JSON.parse(t):t}catch(e){return Or.error("[PP CLIENT] Failed to parse input in safeParse:",t),{}}}const xr="payment_inbox";class Tr extends Nr{peerPayWalletClient;_authFetchInstance;constructor(t){const{messageBoxHost:e="https://messagebox.babbage.systems",walletClient:i,enableLogging:r=!1}=t;super({host:e,walletClient:i,enableLogging:r}),this.peerPayWalletClient=i}get authFetchInstance(){return null!==this._authFetchInstance&&void 0!==this._authFetchInstance||(this._authFetchInstance=new Je(this.peerPayWalletClient)),this._authFetchInstance}async createPaymentToken(t){if(t.amount<=0)throw new Error("Invalid payment details: recipient and valid amount are required");const e=await $e(this.peerPayWalletClient),i=await $e(this.peerPayWalletClient);Or.log(`[PP CLIENT] Derivation Prefix: ${e}`),Or.log(`[PP CLIENT] Derivation Suffix: ${i}`);const{publicKey:r}=await this.peerPayWalletClient.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${e} ${i}`,counterparty:t.recipient});if(Or.log(`[PP CLIENT] Derived Public Key: ${r}`),null==r||""===r.trim())throw new Error("Failed to derive recipient’s public key");const n=(new ne).lock(bt.fromString(r).toAddress()).toHex();Or.log(`[PP CLIENT] Locking Script: ${n}`);const s=await this.peerPayWalletClient.createAction({description:"PeerPay payment",outputs:[{satoshis:t.amount,lockingScript:n,customInstructions:JSON.stringify({derivationPrefix:e,derivationSuffix:i,payee:t.recipient}),outputDescription:"Payment for PeerPay transaction"}],options:{randomizeOutputs:!1}});if(void 0===s.tx)throw new Error("Transaction creation failed!");return Or.log("[PP CLIENT] Payment Action:",s),{customInstructions:{derivationPrefix:e,derivationSuffix:i},transaction:s.tx,amount:t.amount}}async sendPayment(t){if(null==t.recipient||""===t.recipient.trim()||t.amount<=0)throw new Error("Invalid payment details: recipient and valid amount are required");const e=await this.createPaymentToken(t);await this.sendMessage({recipient:t.recipient,messageBox:xr,body:JSON.stringify(e)})}async sendLivePayment(t){const e=await this.createPaymentToken(t);try{await this.sendLiveMessage({recipient:t.recipient,messageBox:xr,body:JSON.stringify(e)})}catch(i){Or.warn("[PP CLIENT] sendLiveMessage failed, falling back to HTTP:",i),await this.sendMessage({recipient:t.recipient,messageBox:xr,body:JSON.stringify(e)})}}async listenForLivePayments({onPayment:t}){await this.listenForLiveMessages({messageBox:xr,onMessage:e=>{Or.log("[MB CLIENT] Received Live Payment:",e);const i={messageId:e.messageId,sender:e.sender,token:Ar(e.body)};Or.log("[PP CLIENT] Converted PeerMessage to IncomingPayment:",i),t(i)}})}async acceptPayment(t){try{Or.log(`[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:0,protocol:"wallet payment"}],description:"PeerPay Payment"});return Or.log(`[PP CLIENT] Payment internalized successfully: ${JSON.stringify(e,null,2)}`),Or.log(`[PP CLIENT] Acknowledging payment with messageId: ${t.messageId}`),await this.acknowledgeMessage({messageIds:[t.messageId]}),{payment:t,paymentResult:e}}catch(t){return Or.error(`[PP CLIENT] Error accepting payment: ${String(t)}`),"Unable to receive payment!"}}async rejectPayment(t){if(Or.log(`[PP CLIENT] Rejecting payment: ${JSON.stringify(t,null,2)}`),t.token.amount-1e3<1e3){Or.log("[PP CLIENT] Payment amount too small after fee, just acknowledging.");try{Or.log(`[PP CLIENT] Attempting to acknowledge message ${t.messageId}...`),null!==this.authFetch&&void 0!==this.authFetch||Or.warn("[PP CLIENT] Warning: authFetch is undefined! Ensure PeerPayClient is initialized correctly."),Or.log("[PP CLIENT] authFetch instance:",this.authFetch);const e=await this.acknowledgeMessage({messageIds:[t.messageId]});Or.log(`[PP CLIENT] Acknowledgment response: ${e}`)}catch(t){if(null==t||"object"!=typeof t||!("message"in t)||"string"!=typeof t.message||!t.message.includes("401"))throw Or.error(`[PP CLIENT] Error acknowledging message: ${t.message}`),t;Or.warn(`[PP CLIENT] Authentication issue while acknowledging: ${t.message}`)}}else{Or.log("[PP CLIENT] Accepting payment before refunding..."),await this.acceptPayment(t),Or.log(`[PP CLIENT] Sending refund of ${t.token.amount-1e3} to ${t.sender}...`),await this.sendPayment({recipient:t.sender,amount:t.token.amount-1e3}),Or.log("[PP CLIENT] Payment successfully rejected and refunded.");try{Or.log(`[PP CLIENT] Acknowledging message ${t.messageId} after refunding...`),await this.acknowledgeMessage({messageIds:[t.messageId]}),Or.log("[PP CLIENT] Acknowledgment after refund successful.")}catch(t){Or.error(`[PP CLIENT] Error acknowledging message after refund: ${t.message}`)}}}async listIncomingPayments(){return(await this.listMessages({messageBox:xr})).map((t=>{const e=Ar(t.body);return{messageId:t.messageId,sender:t.sender,token:e}}))}}return e})()));
|