@bsv/message-box-client 1.4.0 → 1.4.1

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.
@@ -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:()=>$s,PeerPayClient:()=>Ws,STANDARD_PAYMENT_MESSAGEBOX:()=>zs});var i={};t.r(i),t.d(i,{Decoder:()=>Ns,Encoder:()=>Os,PacketType:()=>Ps,protocol:()=>_s});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 s=t.length>0?t.length:1;for(let e=s-1;e>=0;e--){const s=void 0===t[e]?0:t[e];i=i<<r.WORD_SIZE_BIGINT|BigInt(s&Number(r.WORD_MASK))}this._magnitude=i,this._sign=e,this._nominalWordLength=s,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,s=i;if("le"!==e&&"be"!==e||(s=e,r=10),"number"!=typeof t)if(Array.isArray(t))this.initArray(t,s);else if("string"==typeof t){"hex"===r&&(r=16),this.assert("number"==typeof r&&r===(0|r)&&r>=2&&r<=36,"Base must be an integer between 2 and 36");const e=t.toString().replace(/\s+/g,"");let i=0,n=0;e.startsWith("-")?(i++,n=1):e.startsWith("+")&&i++;const a=e.substring(i);if(0===a.length)return this._initializeState(0n,1===n&&e.startsWith("-")?1:0),void this.normSign();if(16===r){let t;if("le"===s){const t=[];let e=a;e.length%2!=0&&(e="0"+e);for(let i=0;i<e.length;i+=2){const r=e.substring(i,i+2),s=parseInt(r,16);if(isNaN(s))throw new Error("Invalid character in "+e);t.push(s)}return this.initArray(t,"le"),this._sign=n,void this.normSign()}try{t=BigInt("0x"+a)}catch(t){throw new Error("Invalid character in "+a)}this._initializeState(t,n),this.normSign()}else try{if(this._parseBaseString(a,r),this._sign=n,this.normSign(),"le"===s){const t=this._sign;this.initArray(this.toArray("be"),"le"),this._sign=t,this.normSign()}}catch(t){const e=t;if(e.message.includes("Invalid character in string")||e.message.includes("Invalid digit for base")||e.message.startsWith("Invalid character:"))throw new Error("Invalid character");throw e}}else 0!==t?this.assert(!1,"Unsupported input type for BigNumber constructor"):this._initializeState(0n,0);else this.initNumber(t,s)}_bigIntToStringInBase(t,e){if(0n===t)return"0";if(e<2||e>36)throw new Error("Base must be between 2 and 36");let i="",r=t>0n?t:-t;const s=BigInt(e);for(;r>0n;)i="0123456789abcdefghijklmnopqrstuvwxyz"[Number(r%s)]+i,r/=s;return i}_parseBaseString(t,e){if(0===t.length)return this._magnitude=0n,void this._finishInitialization();this._magnitude=0n;const i=BigInt(e);let s=r.groupSizes[e],n=BigInt(r.groupBases[e]);0!==s&&0n!==n||(s=Math.floor(Math.log(67108863)/Math.log(e)),0===s&&(s=1),n=i**BigInt(s));let a=0;const o=t.length;let c=o%s;if(0===c&&o>0&&(c=s),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+s),r=BigInt(this._parseBaseWord(i,e));this._magnitude=this._magnitude*n+r,a+=s}this._finishInitialization()}_parseBaseWord(t,e){let i=0;for(let r=0;r<t.length;r++){const s=t.charCodeAt(r);let n;if(s>=48&&s<=57)n=s-48;else if(s>=65&&s<=90)n=s-65+10;else{if(!(s>=97&&s<=122))throw new Error("Invalid character: "+t[r]);n=s-97+10}if(n>=e)throw new Error("Invalid character");i=i*e+n}return i}_initializeState(t,e){this._magnitude=t,this._sign=0n===t?0:e,this._finishInitialization()}_finishInitialization(){if(0n===this._magnitude)this._nominalWordLength=1,this._sign=0;else{const t=this._magnitude.toString(2).length;this._nominalWordLength=Math.max(1,Math.ceil(t/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],s=BigInt(r.groupBases[t]);0!==i&&0n!==s||(i=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(t)),0===i&&(i=1),s=BigInt(t)**BigInt(i));let n="",a=this._magnitude;for(;a>0n;){const e=a%s;a/=s;const o=this._bigIntToStringInBase(e,t);if(a>0n){const t=i-o.length;n=t>0&&t<r.zeros.length?r.zeros[t]+o+n:t>0?"0".repeat(t)+o+n:o+n}else n=o+n}if(e>0)for(;n.length<e;)n="0"+n;return(1===this._sign?"-":"")+n}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 s=e?1:-1;for(let e=0;e<t.length;++e){if(0n===i&&r>=0&&r<t.length)t[r]=0;else{if(!(r>=0&&r<t.length))break;t[r]=Number(0xffn&i)}i>>=8n,r+=s}}toArray(t="be",e){this.strip();const i=this.byteLength(),r=e??Math.max(1,i);this.assert(i<=r,"byte array longer than desired length"),this.assert(r>0,"Requested array length <= 0");const s=new Array(r).fill(0);return 0n===this._magnitude&&r>0?s:0n===this._magnitude&&0===r?[]:(this.toArrayLikeGeneric(s,"le"===t),s)}bitLength(){return 0n===this._magnitude?0:this._magnitude.toString(2).length}static toBitArray(t){const e=t.bitLength();if(0===e)return[];const i=new Array(e),r=t._magnitude;for(let t=0;t<e;t++)i[t]=0n!==(r>>BigInt(t)&1n)?1:0;return i}toBitArray(){return 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 s=new r(0n);return s._initializeState(i,0),s}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),s=new r(0n);return s._setValueFromSigned(t),s}return this.clone()}isNeg(){return 1===this._sign&&0n!==this._magnitude}neg(){return this.clone().ineg()}ineg(){return 0n!==this._magnitude&&(this._sign=1===this._sign?0:1),this}_iuop(t,e){const i=e(this._magnitude,t._magnitude),r=e===((t,e)=>t^e);let s=this._nominalWordLength;return r&&(s=Math.max(this.length,t.length)),this._magnitude=i,this._finishInitialization(),r&&(this._nominalWordLength=Math.max(this._nominalWordLength,s)),this.strip()}iuor(t){return this._iuop(t,((t,e)=>t|e))}iuand(t){return this._iuop(t,((t,e)=>t&e))}iuxor(t){return this._iuop(t,((t,e)=>t^e))}_iop(t,e){return this.assert(0===this._sign&&0===t._sign),this._iuop(t,e)}ior(t){return this._iop(t,((t,e)=>t|e))}iand(t){return this._iop(t,((t,e)=>t&e))}ixor(t){return this._iop(t,((t,e)=>t^e))}_uop_new(t,e){return this.length>=t.length?this.clone()[e](t):t.clone()[e](this)}or(t){return this.assert(0===this._sign&&0===t._sign),this._uop_new(t,"iuor")}uor(t){return this._uop_new(t,"iuor")}and(t){return this.assert(0===this._sign&&0===t._sign),this._uop_new(t,"iuand")}uand(t){return this._uop_new(t,"iuand")}xor(t){return this.assert(0===this._sign&&0===t._sign),this._uop_new(t,"iuxor")}uxor(t){return this._uop_new(t,"iuxor")}inotn(t){this.assert("number"==typeof t&&t>=0);const e=(1n<<BigInt(t))-1n;this._magnitude=~this._magnitude&e;const i=0===t?1:Math.ceil(t/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 s=Math.floor(t/r.wordSize)+1;return this._nominalWordLength=Math.max(this._nominalWordLength,s),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(),s=t.clone(),n=i.isNeg(),a=s.isOdd();for(n&&i.ineg();!s.isZero();)s.isOdd()&&e.imul(i),i.isqr(),s.iushrn(1);return n&&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 s=0===t?1:Math.max(1,Math.ceil(t/r.wordSize));return this._nominalWordLength=s,this._finishInitialization(),this._nominalWordLength=Math.max(this._nominalWordLength,s),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 s=this._getSignedValue(),n=t._getSignedValue();let a=null,o=null;"mod"!==e&&(a=s/n),"div"!==e&&(o=s%n,!0===i&&o<0n&&(o+=n<0n?-n:n));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 s=e/i;const n=e%i;if(0n===n){const t=new r(0n);return t._setValueFromSigned(s),t}2n*(n<0n?-n:n)>=(i<0n?-i:i)&&(e>0n&&i>0n||e<0n&&i<0n?s+=1n:s-=1n);const a=new r(0n);return a._setValueFromSigned(s),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,s=1n,n=0n,a=0n,o=1n;for(;0n!==i;){const t=e/i;let r=i;i=e%i,e=r,r=n,n=s-t*n,s=r,r=o,o=a-t*o,a=r}const c=new r(0n);c._setValueFromSigned(s);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 s=new r(0n);return s._initializeState(e,0),s}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,s="";if("little"===e){const e=t.length-1;let r=t[e];128&r&&(i=1,r&=127),s+=(r<16?"0":"")+r.toString(16);for(let i=e-1;i>=0;i--){const e=t[i];s+=(e<16?"0":"")+e.toString(16)}}else{let e=t[0];128&e&&(i=1,e&=127),s+=(e<16?"0":"")+e.toString(16);for(let e=1;e<t.length;e++){const i=t[e];s+=(i<16?"0":"")+i.toString(16)}}const n=""===s?0n:BigInt("0x"+s),a=new r(0n);return a._initializeState(n,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,s=8388607&t,n=!!(8388608&t);if(e&&n)throw new Error("negative bit set");if(0===i&&0===s){if(n&&e)throw new Error("negative bit set for zero value");return new r(0n)}const a=new r(s);return i<=3?a.iushrn(8*(3-i)):a.iushln(8*(i-3)),n&&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 s,n=i.length;if(0!==n||e.isZero()||(i=[0],n=1),e.isZero()&&(n=0,i=[]),0===n)s=0;else if(n<=3){s=0;for(let t=0;t<n;t++)s=s<<8|i[t]}else s=i[0]<<16|i[1]<<8|i[2];8388608&s&&n<=255&&(s>>>=8,n++);let a=n<<24|s;return t&&(a|=8388608),a>>>0}static fromScriptNum(t,e=!1,i){if(void 0!==i&&t.length>i)throw new Error("script number overflow");if(0===t.length)return new 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,s=1n,n=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&s)&&(s+=a),s>>=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&n)&&(n+=a),n>>=1n}e>=i?(e-=i,s-=n):(i-=e,n-=s)}let o;if(1n===e)o=s;else if(1n===i)o=n;else if(0n===e&&1n===i)o=n;else{if(0n!==i||1n!==e)throw new Error("_invmp: GCD is not 1, inverse does not exist. aVal="+e+", bVal="+i);o=s}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 s{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 n extends s{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(t,e){const i=4194303,r=t.words,s=t.length,n=Math.min(s,9),a=new Array(n+(s>9?1:0)).fill(0);for(let t=0;t<n;t++)a[t]=r[t];let o=n;if(s<=9){const i=new Array(o);for(let t=0;t<o;++t)i[t]=a[t];return e.words=i,void(t.words=[0])}let c=r[9];a[o++]=c&i;const h=new Array(o);for(let t=0;t<o;++t)h[t]=a[t];e.words=h;const d=new Array(Math.max(1,s-9)).fill(0);let u=0;for(let t=10;t<s;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,s=new Array(r).fill(0);for(let t=0;t<i;t++)s[t]=e[t];let n=0;for(let t=0;t<r;t++){const e=0|s[t];n+=977*e,s[t]=67108863&n,n=64*e+(n/67108864|0)}return t.words=s,t}}class a{prime;m;constructor(t){if("k256"===t){const t=new n;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 s=0;for(;!i.isZero()&&0===i.andln(1);)s++,i.iushrn(1);this.assert(!i.isZero());const n=new r(1).toRed(this),a=n.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=s;for(;0!==l.cmp(n);){let t=l,e=0;for(;0!==t.cmp(n);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 s=2;for(;s<i.length;s++)i[s]=this.mul(i[s-1],t);let n=i[0],a=0,o=0,c=e.bitLength()%26;for(0===c&&(c=26),s=e.length-1;s>=0;s--){const t=e.words[s];for(let e=c-1;e>=0;e--){const r=t>>e&1;n!==i[0]&&(n=this.sqr(n)),0!==r||0!==a?(a<<=1,a|=r,o++,(4===o||0===s&&0===e)&&(n=this.mul(n,i[a]),o=0,a=0)):o=0}c=26}return n}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),s=i.isub(r).iushrn(this.shift);let n=s;return s.cmp(this.m)>=0?n=s.isub(this.m):s.cmpn(0)<0&&(n=s.iadd(this.m)),n.forceRed(this)}mul(t,e){if(t.isZero()||e.isZero())return new r(0).forceRed(this);const i=t.mul(e),s=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=i.isub(s).iushrn(this.shift);let a=n;return n.cmp(this.m)>=0?a=n.isub(this.m):n.cmpn(0)<0&&(a=n.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 be,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 fe(null,null);const t=this.z.redInvm(),e=t.redSqr(),i=this.x.redMul(e),r=this.y.redMul(e).redMul(t);return new fe(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),s=t.x.redMul(i),n=this.y.redMul(e.redMul(t.z)),a=t.y.redMul(i.redMul(this.z)),o=r.redSub(s),c=n.redSub(a);if(0===o.cmpn(0))return 0!==c.cmpn(0)?new 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(n.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),s=this.y,n=t.y.redMul(e).redMul(this.z),a=i.redSub(r),o=s.redSub(n);if(0===a.cmpn(0))return 0!==o.cmpn(0)?new 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(s.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(),s=this.y.redSqr(),n=s.redSqr();let a=this.x.redAdd(s).redSqr().redISub(r).redISub(n);a=a.redIAdd(a);const o=r.redAdd(r).redIAdd(r),c=o.redSqr().redISub(a).redISub(a);let h=n.redIAdd(n);h=h.redIAdd(h),h=h.redIAdd(h),t=c,e=o.redMul(a.redISub(c)).redISub(h),i=this.y.redAdd(this.y)}else{const r=this.x.redSqr(),s=this.y.redSqr(),n=s.redSqr();let a=this.x.redAdd(s).redSqr().redISub(r).redISub(n);a=a.redIAdd(a);const o=r.redAdd(r).redIAdd(r),c=o.redSqr();let h=n.redIAdd(n);h=h.redIAdd(h),h=h.redIAdd(h),t=c.redISub(a).redISub(a),e=o.redMul(a.redISub(t)).redISub(h),i=this.y.redMul(this.z),i=i.redIAdd(i)}return new 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),s=i.redMul(t.z);return 0===this.y.redMul(s).redISub(t.y.redMul(r)).cmpn(0)}eqXToP(t){const e=this.z.redSqr(),i=t.toRed(this.curve?.red).redMul(e);if(0===this.x.cmp(i))return!0;const r=t.clone();if(null===this.curve||null==this.curve.redN)throw new Error("Curve or redN is not initialized.");const s=this.curve.redN.redMul(e);for(;r.cmp(this.curve.p)<0;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(i.redIAdd(s),0===this.x.cmp(i))return!0}return!1}inspect(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"}isInfinity(){return 0===this.z.cmpn(0)}}const 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 s=i-0;d(s%4==0);const n=new Array(s/4);for(let e=0,i=0;e<n.length;e++,i+=4){let s;s="big"===r?t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3]:t[i+3]<<24|t[i+2]<<16|t[i+1]<<8|t[i],n[e]=s>>>0}return n}(t,0,t.length-e,this.endian);for(let e=0;e<t.length;e+=this._delta32)this._update(t,e)}return this}digest(){return this.update(this._pad()),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 s,n;for(r[0]=128,s=1;s<i;s++)r[s]=0;if(t<<=3,"big"===this.endian){for(n=8;n<this.padLength;n++)r[s++]=0;r[s++]=0,r[s++]=0,r[s++]=0,r[s++]=0,r[s++]=t>>>24&255,r[s++]=t>>>16&255,r[s++]=t>>>8&255,r[s++]=255&t}else for(r[s++]=255&t,r[s++]=t>>>8&255,r[s++]=t>>>16&255,r[s++]=t>>>24&255,r[s++]=0,r[s++]=0,r[s++]=0,r[s++]=0,n=8;n<this.padLength;n++)r[s++]=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 s=t.charCodeAt(r);s<128?i[e++]=s:s<2048?(i[e++]=s>>6|192,i[e++]=63&s|128):l(t,r)?(s=65536+((1023&s)<<10)+(1023&t.charCodeAt(++r)),i[e++]=s>>18|240,i[e++]=s>>12&63|128,i[e++]=s>>6&63|128,i[e++]=63&s|128):(i[e++]=s>>12|224,i[e++]=s>>6&63|128,i[e++]=63&s|128)}}else{(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 s=0;s<t.length;s++){let n=t[s];"little"===e&&(n=p(n)),i+=7===(r=n.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){let e="";for(const i of t)e+=i.toString(16).padStart(2,"0");return e}function y(t,e){const i=new Array(4*t.length);for(let r=0,s=0;r<t.length;r++,s+=4){const n=t[r];"big"===e?(i[s]=n>>>24,i[s+1]=n>>>16&255,i[s+2]=n>>>8&255,i[s+3]=255&n):(i[s+3]=n>>>24,i[s+2]=n>>>16&255,i[s+1]=n>>>8&255,i[s]=255&n)}return i}function m(t,e){return t>>>e|t<<32-e}function w(t,e){return t<<e|t>>>32-e}function I(t,e){return t+e>>>0}function v(t,e,i){return t+e+i>>>0}function k(t,e,i,r){return t+e+i+r>>>0}function S(t,e,i,r,s){return t+e+i+r+s>>>0}function E(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?P(e,i,r):0}function _(t,e,i){return t&e^~t&i}function P(t,e,i){return t&e^t&i^e&i}function O(t){return m(t,2)^m(t,13)^m(t,22)}function x(t){return m(t,6)^m(t,11)^m(t,25)}function N(t){return m(t,17)^m(t,19)^t>>>10}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],T=[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],C=[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],R=[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 B(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 L(t){return t<=15?0:t<=31?1518500249:t<=47?1859775393:t<=63?2400959708:2840853838}function M(t){return t<=15?1352829926:t<=31?1548603684:t<=47?1836072691:t<=63?2053994217:0}class D 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],s=this.h[1],n=this.h[2],a=this.h[3],o=this.h[4],c=r,h=s,d=n,u=a,l=o;for(let f=0;f<80;f++)i=I(w(k(r,B(f,s,n,a),t[A[f]+e],L(f)),C[f]),o),r=o,o=a,a=w(n,10),n=s,s=i,i=I(w(k(c,B(79-f,h,d,u),t[T[f]+e],M(f)),R[f]),l),c=l,l=u,u=w(d,10),d=h,h=i;i=v(this.h[1],n,u),this.h[1]=v(this.h[2],a,l),this.h[2]=v(this.h[3],o,c),this.h[3]=v(this.h[4],r,h),this.h[4]=v(this.h[0],s,d),this.h[0]=i}_digest(){return y(this.h,"little")}_digestHex(){return b(this.h,"little")}}class F{h;constructor(){this.h=new It}update(t,e){const i=Uint8Array.from(f(t,e));return this.h.update(i),this}digest(){return Array.from(this.h.digest())}digestHex(){return g(this.h.digest())}}class V 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]=w(i[r-3]^i[r-8]^i[r-14]^i[r-16],1);let s=this.h[0],n=this.h[1],a=this.h[2],o=this.h[3],c=this.h[4];for(r=0;r<i.length;r++){const t=~~(r/20),e=S(w(s,5),E(t,n,a,o),c,i[r],this.k[t]);c=o,o=a,a=w(n,30),n=s,s=e}this.h[0]=I(this.h[0],s),this.h[1]=I(this.h[1],n),this.h[2]=I(this.h[2],a),this.h[3]=I(this.h[3],o),this.h[4]=I(this.h[4],c)}_digest(){return y(this.h,"big")}_digestHex(){return b(this.h,"big")}}class H{h;blockSize=64;outSize=32;constructor(t){const e=Uint8Array.from(f(t,"hex"));this.h=new At(vt,e)}update(t,e){return this.h.update(Uint8Array.from(f(t,e))),this}digest(){return Array.from(this.h.digest())}digestHex(){return g(this.h.digest())}}class q{h;blockSize=128;outSize=32;constructor(t){const e=Uint8Array.from(f(t,"hex"));this.h=new At(Nt,e)}update(t,e){return this.h.update(Uint8Array.from(f(t,e))),this}digest(){return Array.from(this.h.digest())}digestHex(){return g(this.h.digest())}}const U=(t,e)=>(new F).update(t,e).digest(),K=(t,e)=>{const i=(new F).update(t,e).digest();return(new F).update(i).digest()},$=(t,e)=>{const i=(new F).update(t,e).digest();return(new D).update(i).digest()},j=(t,e,i)=>new H(t).update(e,i).digest();function z(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, got ${t}`)}function W(t,...e){if(!((i=t)instanceof Uint8Array||ArrayBuffer.isView(i)&&"Uint8Array"===i.constructor.name))throw new Error("Uint8Array expected");var i;if(e.length>0&&!e.includes(t.length)){const i=e.join(",");throw new Error(`Uint8Array expected of length ${i}, got length=${t.length}`)}}function G(t,e=!0){if(!0===t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&!0===t.finished)throw new Error("Hash#digest() has already been called")}function X(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function J(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Y(t){return"string"==typeof t&&(t=function(t){if("string"!=typeof t)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(t))}(t)),W(t),t}class Z{}function Q(t){const e=e=>t().update(Y(e)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}const tt=BigInt(2**32-1),et=BigInt(32);function it(t,e=!1){return e?{h:Number(t&tt),l:Number(t>>et&tt)}:{h:0|Number(t>>et&tt),l:0|Number(t&tt)}}const rt=(t,e,i)=>t>>>i,st=(t,e,i)=>t<<32-i|e>>>i,nt=(t,e,i)=>t>>>i|e<<32-i,at=(t,e,i)=>t<<32-i|e>>>i,ot=(t,e,i)=>t<<64-i|e>>>i-32,ct=(t,e,i)=>t>>>i-32|e<<64-i;function ht(t,e,i,r){const s=(e>>>0)+(r>>>0);return{h:t+i+(s/2**32|0)|0,l:0|s}}const dt=(t,e,i)=>(t>>>0)+(e>>>0)+(i>>>0),ut=(t,e,i,r)=>e+i+r+(t/2**32|0)|0,lt=(t,e,i,r)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),ft=(t,e,i,r,s)=>e+i+r+s+(t/2**32|0)|0,pt=(t,e,i,r,s)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0)+(s>>>0),bt=(t,e,i,r,s,n)=>e+i+r+s+n+(t/2**32|0)|0;class gt extends Z{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,i,r){super(),this.blockLen=t,this.outputLen=e,this.padOffset=i,this.isLE=r,this.buffer=new Uint8Array(t),this.view=J(this.buffer)}update(t){G(this),W(t=Y(t));const{view:e,buffer:i,blockLen:r}=this,s=t.length;for(let n=0;n<s;){const a=Math.min(r-this.pos,s-n);if(a!==r)i.set(t.subarray(n,n+a),this.pos),this.pos+=a,n+=a,this.pos===r&&(this.process(e,0),this.pos=0);else{const e=J(t);for(;r<=s-n;n+=r)this.process(e,n)}}return this.length+=t.length,this.roundClean(),this}digestInto(t){G(this),function(t,e){W(t);const i=e.outputLen;if(t.length<i)throw new Error(`digestInto() expects output buffer of length at least ${i}`)}(t,this),this.finished=!0;const{buffer:e,view:i,blockLen:r,isLE:s}=this;let{pos:n}=this;e[n++]=128,X(this.buffer.subarray(n)),this.padOffset>r-n&&(this.process(i,0),n=0);for(let t=n;t<r;t++)e[t]=0;!function(t,e,i,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,i,r);const s=BigInt(32),n=BigInt(4294967295),a=Number(i>>s&n),o=Number(i&n),c=r?4:0,h=r?0:4;t.setUint32(e+c,a,r),t.setUint32(e+h,o,r)}(i,r-8,BigInt(8*this.length),s),this.process(i,0);const a=J(t),o=this.outputLen;if(o%4!=0)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t<c;t++)a.setUint32(4*t,h[t],s)}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const i=t.slice(0,e);return this.destroy(),i}_cloneInto(t){t||=new this.constructor,t.set(...this.get());const{blockLen:e,buffer:i,length:r,finished:s,destroyed:n,pos:a}=this;return t.destroyed=n,t.finished=s,t.length=r,t.pos=a,r%e!=0&&t.buffer.set(i),t}clone(){return this._cloneInto()}}const yt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),mt=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),wt=new Uint32Array(64);class It extends gt{A=0|yt[0];B=0|yt[1];C=0|yt[2];D=0|yt[3];E=0|yt[4];F=0|yt[5];G=0|yt[6];H=0|yt[7];constructor(t=32){super(64,t,8,!1)}get(){const{A:t,B:e,C:i,D:r,E:s,F:n,G:a,H:o}=this;return[t,e,i,r,s,n,a,o]}set(t,e,i,r,s,n,a,o){this.A=0|t,this.B=0|e,this.C=0|i,this.D=0|r,this.E=0|s,this.F=0|n,this.G=0|a,this.H=0|o}process(t,e){for(let i=0;i<16;i++,e+=4)wt[i]=t.getUint32(e);for(let t=16;t<64;t++){const e=wt[t-15],r=wt[t-2],s=m(i=e,7)^m(i,18)^i>>>3,n=N(r);wt[t]=I(I(s,wt[t-7]),I(n,wt[t-16]))}var i;let{A:r,B:s,C:n,D:a,E:o,F:c,G:h,H:d}=this;for(let t=0;t<64;t++){const e=S(d,x(o),_(o,c,h),mt[t],wt[t]),i=I(O(r),P(r,s,n));d=h,h=c,c=o,o=I(a,e),a=n,n=s,s=r,r=I(e,i)}this.A=I(this.A,r),this.B=I(this.B,s),this.C=I(this.C,n),this.D=I(this.D,a),this.E=I(this.E,o),this.F=I(this.F,c),this.G=I(this.G,h),this.H=I(this.H,d)}roundClean(){X(wt)}destroy(){X(this.buffer),this.set(0,0,0,0,0,0,0,0)}}const vt=Q((()=>new It)),kt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),St=function(t,e=!1){const i=t.length,r=new Uint32Array(i),s=new Uint32Array(i);for(let n=0;n<i;n++){const{h:i,l:a}=it(t[n],e);r[n]=i,s[n]=a}return[r,s]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((t=>BigInt(t)))),Et=St[0],_t=St[1],Pt=new Uint32Array(80),Ot=new Uint32Array(80);class xt extends gt{Ah=0|kt[0];Al=0|kt[1];Bh=0|kt[2];Bl=0|kt[3];Ch=0|kt[4];Cl=0|kt[5];Dh=0|kt[6];Dl=0|kt[7];Eh=0|kt[8];El=0|kt[9];Fh=0|kt[10];Fl=0|kt[11];Gh=0|kt[12];Gl=0|kt[13];Hh=0|kt[14];Hl=0|kt[15];constructor(t=64){super(128,t,16,!1)}get(){const{Ah:t,Al:e,Bh:i,Bl:r,Ch:s,Cl:n,Dh:a,Dl:o,Eh:c,El:h,Fh:d,Fl:u,Gh:l,Gl:f,Hh:p,Hl:b}=this;return[t,e,i,r,s,n,a,o,c,h,d,u,l,f,p,b]}set(t,e,i,r,s,n,a,o,c,h,d,u,l,f,p,b){this.Ah=0|t,this.Al=0|e,this.Bh=0|i,this.Bl=0|r,this.Ch=0|s,this.Cl=0|n,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|h,this.Fh=0|d,this.Fl=0|u,this.Gh=0|l,this.Gl=0|f,this.Hh=0|p,this.Hl=0|b}process(t,e){for(let i=0;i<16;i++,e+=4)Pt[i]=t.getUint32(e),Ot[i]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|Pt[t-15],i=0|Ot[t-15],r=nt(e,i,1)^nt(e,i,8)^rt(e,0,7),s=at(e,i,1)^at(e,i,8)^st(e,i,7),n=0|Pt[t-2],a=0|Ot[t-2],o=nt(n,a,19)^ot(n,a,61)^rt(n,0,6),c=at(n,a,19)^ct(n,a,61)^st(n,a,6),h=lt(s,c,Ot[t-7],Ot[t-16]),d=ft(h,r,o,Pt[t-7],Pt[t-16]);Pt[t]=0|d,Ot[t]=0|h}let{Ah:i,Al:r,Bh:s,Bl:n,Ch:a,Cl:o,Dh:c,Dl:h,Eh:d,El:u,Fh:l,Fl:f,Gh:p,Gl:b,Hh:g,Hl:y}=this;for(let t=0;t<80;t++){const e=nt(d,u,14)^nt(d,u,18)^ot(d,u,41),m=at(d,u,14)^at(d,u,18)^ct(d,u,41),w=d&l^~d&p,I=pt(y,m,u&f^~u&b,_t[t],Ot[t]),v=bt(I,g,e,w,Et[t],Pt[t]),k=0|I,S=nt(i,r,28)^ot(i,r,34)^ot(i,r,39),E=at(i,r,28)^ct(i,r,34)^ct(i,r,39),_=i&s^i&a^s&a,P=r&n^r&o^n&o;g=0|p,y=0|b,p=0|l,b=0|f,l=0|d,f=0|u,({h:d,l:u}=ht(0|c,0|h,0|v,0|k)),c=0|a,h=0|o,a=0|s,o=0|n,s=0|i,n=0|r;const O=dt(E,P,k);i=ut(O,S,_,v),r=0|O}({h:i,l:r}=ht(i,r,this.Ah,this.Al)),({h:s,l:n}=ht(s,n,this.Bh,this.Bl)),({h:a,l:o}=ht(a,o,this.Ch,this.Cl)),({h:c,l:h}=ht(c,h,this.Dh,this.Dl)),({h:d,l:u}=ht(d,u,this.Eh,this.El)),({h:l,l:f}=ht(l,f,this.Fh,this.Fl)),({h:p,l:b}=ht(p,b,this.Gh,this.Gl)),({h:g,l:y}=ht(g,y,this.Hh,this.Hl)),this.set(i,r,s,n,a,o,c,h,d,u,l,f,p,b,g,y)}roundClean(){X(Pt,Ot)}destroy(){X(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Nt=Q((()=>new xt));class At extends Z{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){super(),function(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash should be wrapped by utils.createHasher");z(t.outputLen),z(t.blockLen)}(t);const i=Y(e);if(this.iHash=t.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,s=new Uint8Array(r);s.set(i.length>r?t.create().update(i).digest():i);for(let t=0;t<s.length;t++)s[t]^=54;this.iHash.update(s),this.oHash=t.create();for(let t=0;t<s.length;t++)s[t]^=106;this.oHash.update(s),X(s)}update(t){return G(this),this.iHash.update(t),this}digestInto(t){G(this),W(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});const{oHash:e,iHash:i,finished:r,destroyed:s,blockLen:n,outputLen:a}=this;return t.finished=r,t.destroyed=s,t.blockLen=n,t.outputLen=a,t.oHash=e._cloneInto(t.oHash??void 0),t.iHash=i._cloneInto(t.iHash??void 0),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Tt=t=>{let e="";for(const r of t)e+=(i=r.toString(16)).length%2==1?"0"+i:i;var i;return e},Ct=(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 Rt(t);case"base64":return Bt(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 s=r;s>65535?i++:s>=55296&&s<=57343&&(s=65533),s<=127?e.push(s):s<=2047?e.push(192|s>>6,128|63&s):s<=65535?e.push(224|s>>12,128|s>>6&63,128|63&s):e.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s)}return e}(t)}},Rt=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},Bt=t=>{const e=[];let i=0,r=0;for(const s of t.replace(/=+$/,""))i=i<<6|"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(s),r+=6,r>=8&&(r-=8,e.push(i>>r&255),i&=(1<<r)-1);return e},Lt=t=>{let e="",i=0;for(let r=0;r<t.length;r++){const s=t[r];if(i>0)i--;else if(s<=127)e+=String.fromCharCode(s);else if(s>=192&&s<=223){i=1;const n=(31&s)<<6|63&t[r+1];e+=String.fromCharCode(n)}else if(s>=224&&s<=239){i=2;const n=(15&s)<<12|(63&t[r+1])<<6|63&t[r+2];e+=String.fromCharCode(n)}else if(s>=240&&s<=247){i=3;const n=(7&s)<<18|(63&t[r+1])<<12|(63&t[r+2])<<6|63&t[r+3],a=55296+(n-65536>>10),o=56320+(n-65536&1023);e+=String.fromCharCode(a,o)}}return e},Mt=(t,e)=>{switch(e){case"hex":return Tt(t);case"utf8":return Lt(t);default:return t}};function Dt(t){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let i,r="";for(i=0;i<t.length;i+=3){const s=t[i],n=i+1<t.length?t[i+1]:0,a=i+2<t.length?t[i+2]:0,o=(3&s)<<4|n>>4,c=(15&n)<<2|a>>6,h=63&a;r+=e.charAt(s>>2)+e.charAt(o),r+=i+1<t.length?e.charAt(c):"=",r+=i+2<t.length?e.charAt(h):"="}return r}const Ft="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Vt=t=>{if(""===t||"string"!=typeof t)throw new Error(`Expected base58 string but got “${t}”`);const e=t.match(/[IOl0]/gmu);if(null!==e)throw new Error(`Invalid base58 character “${e.join("")}”`);const i=t.match(/^1+/gmu),r=null!==i?i[0].length:0,s=(t.length-r)*(Math.log(58)/Math.log(256))+1>>>0,n=new Uint8Array([...new Uint8Array(r),...(t.match(/./gmu)??[]).map((t=>Ft.indexOf(t))).reduce(((t,e)=>t.map((t=>{const i=58*t+e;return e=i>>8,i}))),new Uint8Array(s)).reverse().filter((a=!1,t=>a=a||t))]);var a;return[...n]},Ht=t=>{const e=Array(256).fill(-1);for(let t=0;t<58;++t)e[Ft.charCodeAt(t)]=t;const i=[];for(const r of t){let t=r;for(let r=0;r<i.length;++r){const s=(e[i[r]]<<8)+t;i[r]=Ft.charCodeAt(s%58),t=s/58|0}for(;0!==t;)i.push(Ft.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)},qt=(t,e=[0])=>{let i=K([...e,...t]);return i=[...e,...t,...i.slice(0,4)],Ht(i)},Ut=(t,e,i=1)=>{const r=Vt(t);let s=r.slice(0,i),n=r.slice(i,-4),a=[...s,...n];return a=K(a),r.slice(-4).forEach(((t,e)=>{if(t!==a[e])throw new Error("Invalid checksum")})),"hex"===e&&(s=Tt(s),n=Tt(n)),{prefix:s,data:n}};class Kt{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=Kt.varIntNum(t);return this.write(e),this}writeVarIntBn(t){const e=Kt.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(Wt)),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 Kt;i.writeUInt8(255),i.writeUInt64LEBn(t),e=i.toArray()}return e}}class $t{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(zt)&&(e=e.sub(Wt)),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 jt=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[]},zt=new r(2).pow(new r(63)),Wt=new r(2).pow(new r(64)),Gt=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,Xt=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,Jt=(1n<<256n)-1n;function Yt(t){let e=t>>256n;return e=(t=(t&Jt)+(e<<32n)+977n*e)>>256n,(t=(t&Jt)+(e<<32n)+977n*e)>=Gt&&(t-=Gt),t}const Zt=t=>Yt((t%Gt+Gt)%Gt),Qt=(t,e)=>t>=e?t-e:Gt-(e-t),te=(t,e)=>Yt(t*e),ee=t=>{let e=1n,i=0n,r=Zt(t),s=Gt;for(;r>1n;){const t=s/r;[e,i]=[i-e*t,e],[r,s]=[s-r*t,r]}return Zt(e)},ie=Gt+1n>>2n,re=BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),se=BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),ne=new Map,ae=t=>{const{X:e,Y:i,Z:r}=t;if(0n===i)return{X:0n,Y:1n,Z:0n};const s=te(i,i),n=te(4n,te(e,s)),a=te(3n,te(e,e)),o=Qt(te(a,a),te(2n,n));return{X:o,Y:Qt(te(a,Qt(n,o)),te(8n,te(s,s))),Z:te(2n,te(i,r))}},oe=(t,e)=>{if(0n===t.Z)return e;if(0n===e.Z)return t;const i=te(t.Z,t.Z),r=te(e.Z,e.Z),s=te(t.X,r),n=te(e.X,i),a=te(t.Y,te(r,e.Z)),o=te(e.Y,te(i,t.Z)),c=Qt(n,s),h=Qt(o,a);if(0n===c)return 0n===h?ae(t):{X:0n,Y:1n,Z:0n};const d=te(c,c),u=te(c,d),l=te(s,d),f=Qt(Qt(te(h,h),u),te(2n,l));return{X:f,Y:Qt(te(h,Qt(l,f)),te(a,u)),Z:te(c,te(t.Z,e.Z))}},ce=t=>0n===t.Z?t:{X:t.X,Y:Gt-t.Y,Z:t.Z},he=(t,e,i=5)=>{const r=`${i}:${e.x.toString(16)}:${e.y.toString(16)}`;let s,n=ne.get(r);if(void 0===n){const t=1<<i-1;n=new Array(t),s={X:e.x,Y:e.y,Z:1n},n[0]=s;const a=ae(s);for(let e=1;e<t;e++)n[e]=oe(n[e-1],a);ne.set(r,n)}else s=n[0];const a=[],o=1n<<BigInt(i),c=o>>1n;let h=t;for(;h>0n;)if(0n===(1n&h))a.push(0),h>>=1n;else{let t=h&o-1n;t>c&&(t-=o),a.push(Number(t)),h-=t,h>>=1n}let d={X:0n,Y:1n,Z:0n};for(let t=a.length-1;t>=0;t--){d=ae(d);const e=a[t];if(0!==e){const t=Math.abs(e)>>1,i=e>0?n[t]:ce(n[t]);d=oe(d,i)}}return d},de=t=>{let e=t%Xt;return e<0n&&(e+=Xt),e},ue=(t,e)=>de(t*e),le=t=>{let e=1n,i=0n,r=de(t),s=Xt;for(;r>1n;){const t=s/r;[e,i]=[i-e*t,e],[r,s]=[s-r*t,r]}return de(e)};class fe extends c{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 fe(t.slice(1,33),t.slice(33,65))}if((2===t[0]||3===t[0])&&t.length-1==32)return fe.fromX(t.slice(1,33),3===t[0]);throw new Error("Unknown point format")}static fromString(t){const e=Ct(t,"hex");return fe.fromDER(e)}static fromX(t,e){let i=(t=>r.isBN(t)?BigInt("0x"+t.toString(16)):"string"==typeof t?BigInt("0x"+t):Array.isArray(t)?BigInt("0x"+Tt(t)):BigInt(t))(t);i=Zt(i);var s;const n=(t=>{const e=((t,e)=>{let i=1n;t=Zt(t);let r=e;for(;r>0n;)1n===(1n&r)&&(i=te(i,t)),t=te(t,t),r>>=1n;return i})(t,ie);return te(e,e)===Zt(t)?e:null})((t=>Yt(t+7n))(te(te(s=i,s),i)));if(null===n)throw new Error("Invalid point");let a=n;(1n&a)!==(e?1n:0n)&&(a=Qt(Gt,a));const o=new r(i.toString(16),16),c=new r(a.toString(16),16);return new fe(o,c)}static fromJSON(t,e){"string"==typeof t&&(t=JSON.parse(t));const i=new fe(t[0],t[1],e);if("object"!=typeof t[2])return i;const r=t=>new fe(t[0],t[1],e),s=t[2];return i.precomputed={beta:null,doubles:"object"==typeof s.doubles&&null!==s.doubles?{step:s.doubles.step,points:[i].concat(s.doubles.points.map(r))}:void 0,naf:"object"==typeof s.naf&&null!==s.naf?{wnd:s.naf.wnd,points:[i].concat(s.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 s;return s=t?[this.getY().isEven()?2:3].concat(r):[4].concat(r,this.getY().toArray("be",i)),"hex"!==e?s:Tt(s)}toString(){return this.encode(!0,"hex")}toJSON(){return null==this.precomputed?[this.x,this.y]:[this.x,this.y,"object"==typeof this.precomputed&&null!==this.precomputed?{doubles:null!=this.precomputed.doubles?{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)}:void 0,naf:null!=this.precomputed.naf?{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}:void 0}:void 0]}inspect(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+(this.x?.fromRed()?.toString(16,2)??"undefined")+" y: "+(this.y?.fromRed()?.toString(16,2)??"undefined")+">"}isInfinity(){return this.inf}add(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return new fe(null,null);if(0===this.x?.cmp(t.x??new r(0)))return new fe(null,null);const e={X:BigInt("0x"+this.x.fromRed().toString(16)),Y:BigInt("0x"+this.y.fromRed().toString(16)),Z:1n},i={X:BigInt("0x"+t.x.fromRed().toString(16)),Y:BigInt("0x"+t.y.fromRed().toString(16)),Z:1n},s=oe(e,i);if(0n===s.Z)return new fe(null,null);const n=ee(s.Z),a=te(n,n),o=te(s.X,a),c=te(s.Y,te(a,n));return new fe(o.toString(16),c.toString(16))}dbl(){if(this.inf)return this;if(null===this.x||null===this.y)throw new Error("Point coordinates cannot be null");const t=BigInt("0x"+this.x.fromRed().toString(16)),e=BigInt("0x"+this.y.fromRed().toString(16));if(0n===e)return new fe(null,null);const i=ae({X:t,Y:e,Z:1n}),r=ee(i.Z),s=te(r,r),n=te(i.X,s),a=te(i.Y,te(s,r));return new fe(n.toString(16),a.toString(16))}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)),this.inf)return this;let e=BigInt("0x"+t.toString(16));const i=e<0n;if(i&&(e=-e),e=Zt(e),0n===e)return new fe(null,null);if(null===this.x||null===this.y)throw new Error("Point coordinates cannot be null");let s,n;this===this.curve.g?(s=re,n=se):(s=BigInt("0x"+this.x.fromRed().toString(16)),n=BigInt("0x"+this.y.fromRed().toString(16)));const a=he(e,{x:s,y:n});if(0n===a.Z)return new fe(null,null);const o=ee(a.Z),c=te(o,o),h=te(a.X,c),d=te(a.Y,te(c,o)),u=new r(h.toString(16),16),l=new r(d.toString(16),16),f=new fe(u,l);return i?f.neg():f}mulAdd(t,e,i){const r=[this,e],s=[t,i];return this._endoWnafMulAdd(r,s)}jmulAdd(t,e,i){const r=[this,e],s=[t,i];return this._endoWnafMulAdd(r,s,!0)}eq(t){return this===t||this.inf===t.inf&&(this.inf||0===(this.x??new 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 fe(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 fe((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 fe(t.x.redMul(i.endo.beta),t.y)};t.beta=e,e.precomputed={beta:null,naf:null!=t.naf?{wnd:t.naf.wnd,points:t.naf.points.map(r)}:void 0,doubles:null!=t.doubles?{step:t.doubles.step,points:t.doubles.points.map(r)}:void 0}}return e}_fixedNafMul(t){if("object"!=typeof this.precomputed||null===this.precomputed)throw new Error("_fixedNafMul requires precomputed values for the point");const e=this._getDoubles(),i=this.curve.getNAF(t,1,this.curve._bitLength);let r=(1<<e.step+1)-(e.step%2==0?2:1);r/=3;const s=[];for(let t=0;t<i.length;t+=e.step){let r=0;for(let s=t+e.step-1;s>=t;s--)r=(r<<1)+i[s];s.push(r)}let n=new h(null,null,null),a=new h(null,null,null);for(let t=r;t>0;t--){for(let i=0;i<s.length;i++){const r=s[i];r===t?a=a.mixedAdd(e.points[i]):r===-t&&(a=a.mixedAdd(e.points[i].neg()))}n=n.add(a)}return n.toP()}_wnafMulAdd(t,e,i,s,n){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<s;i++){const r=e[i]._getNAFPoints(t);a[i]=r.wnd,o[i]=r.points}for(let t=s-1;t>=1;t-=2){const s=t-1,n=t;if(1!==a[s]||1!==a[n]){c[s]=this.curve.getNAF(i[s],a[s],this.curve._bitLength),c[n]=this.curve.getNAF(i[n],a[n],this.curve._bitLength),d=Math.max(c[s].length,d),d=Math.max(c[n].length,d);continue}const h=[e[s],null,null,e[n]];0===(e[s].y??new r(0)).cmp(e[n].y??new r(0))?(h[1]=e[s].add(e[n]),h[2]=e[s].toJ().mixedAdd(e[n].neg())):0===(e[s].y??new r(0)).cmp((e[n].y??new r(0)).redNeg())?(h[1]=e[s].toJ().mixedAdd(e[n]),h[2]=e[s].add(e[n].neg())):(h[1]=e[s].toJ().mixedAdd(e[n]),h[2]=e[s].toJ().mixedAdd(e[n].neg()));const u=[-3,-1,-5,-7,0,7,5,1,3],l=this.curve.getJSF(i[s],i[n]);d=Math.max(l[0].length,d),c[s]=new Array(d),c[n]=new Array(d);for(let t=0;t<d;t++){const e=0|l[0][t],i=0|l[1][t];c[s][t]=u[3*(e+1)+(i+1)],c[n][t]=0,o[s]=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<s;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),n=new r(2);for(let t=0;t<s;t++){const e=l[t];let r;0!==e.cmpn(0)&&(r=e.isNeg()?o[t][e.neg().sub(i).div(n).toNumber()].neg():o[t][e.sub(i).div(n).toNumber()],u="affine"===r.type?u.mixedAdd(r):u.add(r))}}for(let t=0;t<s;t++)o[t]=[];return!0===n?u:u.toP()}_endoWnafMulAdd(t,e,i){const r=new Array(2*t.length),s=new Array(2*t.length);let n;for(n=0;n<t.length;n++){const i=this.curve._endoSplit(e[n]);let a=t[n],o=a._getBeta()??new fe(null,null);0!==i.k1.negative&&(i.k1.ineg(),a=a.neg(!0)),0!==i.k2.negative&&(i.k2.ineg(),o=o.neg(!0)),r[2*n]=a,r[2*n+1]=o,s[2*n]=i.k1,s[2*n+1]=i.k2}const a=this._wnafMulAdd(1,r,s,2*n,i);for(let t=0;t<2*n;t++)r[t]=null,s[t]=null;return a}_hasDoubles(t){if(null==this.precomputed)return!1;const e=this.precomputed.doubles;return"object"==typeof e&&e.points.length>=Math.ceil((t.bitLength()+1)/e.step)}_getDoubles(t,e){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.doubles&&null!==this.precomputed.doubles)return this.precomputed.doubles;const i=[this];let r=this;for(let s=0;s<(e??0);s+=t??1){for(let e=0;e<(t??1);e++)r=r.dbl();i.push(r)}return{step:t??1,points:i}}_getNAFPoints(t){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.naf&&null!==this.precomputed.naf)return this.precomputed.naf;const e=[this],i=(1<<t)-1,r=1===i?null:this.dbl();for(let t=1;t<i;t++)null!==r&&(e[t]=e[t-1].add(r));return{wnd:t,points:e}}}let pe;class be{p;red;redN;zero;one;two;g;n;a;b;tinv;zeroA;threeA;endo;_endoWnafT1;_endoWnafT2;_wnafT1;_wnafT2;_wnafT3;_wnafT4;_bitLength;static assert(t,e="Elliptic curve assertion failed"){if(!t)throw new Error(e)}getNAF(t,e,i){const r=new Array(Math.max(t.bitLength(),i)+1);r.fill(0);const s=1<<e+1,n=t.clone();for(let t=0;t<r.length;t++){let e;const i=n.andln(s-1);n.isOdd()?(e=i>(s>>1)-1?(s>>1)-i:i,n.isubn(e)):e=0,r[t]=e,n.iushrn(1)}return r}getJSF(t,e){const i=[[],[]];t=t.clone(),e=e.clone();let r=0,s=0;for(;t.cmpn(-r)>0||e.cmpn(-s)>0;){let n,a,o=t.andln(3)+r&3,c=e.andln(3)+s&3;if(3===o&&(o=-1),3===c&&(c=-1),1&o){const e=t.andln(7)+r&7;n=3!==e&&5!==e||2!==c?o:-o}else n=0;if(i[0].push(n),1&c){const t=e.andln(7)+s&7;a=3!==t&&5!==t||2!==o?c:-c}else a=0;i[1].push(a),2*r===n+1&&(r=1-r),2*s===a+1&&(s=1-s),t.iushrn(1),e.iushrn(1)}return i}static cachedProperty(t,e,i){const r="_"+e;t.prototype[e]=function(){return void 0!==this[r]?this[r]:this[r]=i.call(this)}}static parseBytes(t){return"string"==typeof t?Ct(t,"hex"):t}static intFromLE(t){return new r(t,"hex","le")}constructor(){if(void 0!==pe)return pe;pe=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=fe.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,s;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,s=null!=this.g.x?this.g.x.redMul(e):void 0;if(null!=r&&null!=s&&0===r.cmp(s))i=t[0];else{if(i=t[1],null==this.g)throw new Error("Curve generator point (g) is not defined.");const r=this.g.mul(i)?.x,s=null!=this.g.x?this.g.x.redMul(e):void 0;if(null==r||null==s)throw new Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");be.assert(0===r.cmp(s),"Lambda selection does not match computed beta.")}}return s="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:s}}_getEndoRoots(t){const e=t===this.p?this.red:new o(t),i=new r(2).toRed(e).redInvm(),s=i.redNeg(),n=new r(3).toRed(e).redNeg().redSqrt().redMul(i);return[s.redAdd(n).fromRed(),s.redSub(n).fromRed()]}_getEndoBasis(t){const e=this.n.ushrn(Math.floor(this.n.bitLength()/2));let i,s,n,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===n&&y.cmp(e)<0)i=b.neg(),s=u,n=y.neg(),a=m;else if(void 0!==n&&2==++g)break;b=y,d=h,h=y,f=u,u=m,p=l,l=r}if(void 0===i||void 0===s||void 0===n||void 0===a)throw new Error("Failed to compute Endo Basis values");o=y.neg(),c=m;const w=n.sqr().add(a.sqr());return o.sqr().add(c.sqr()).cmp(w)>=0&&(o=i,c=s),0!==n.negative&&(n=n.neg(),a=a.neg()),0!==o.negative&&(o=o.neg(),c=c.neg()),[{a:n,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],s=r.b.mul(t).divRound(this.n),n=i.b.neg().mul(t).divRound(this.n),a=s.mul(i.a),o=n.mul(r.a),c=s.mul(i.b),h=n.mul(r.b);return{k1:t.sub(a).sub(o),k2:c.add(h).neg()}}validate(t){if(t.inf)return!0;const e=t.x,i=t.y;if(null===e||null===i)throw new Error("Point coordinates cannot be null");const r=this.a.redMul(e),s=e.redSqr().redMul(e).redIAdd(r).redIAdd(this.b);return 0===i.redSqr().redISub(s).cmpn(0)}}class ge{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=Ct(t,e);const s=new class{place;constructor(){this.place=0}};if(48!==t[s.place++])throw new Error("Signature DER must start with 0x30");if(i(t,s)+s.place!==t.length)throw new Error("Signature DER invalid");if(2!==t[s.place++])throw new Error("Signature DER invalid");const n=i(t,s);let a=t.slice(s.place,n+s.place);if(s.place+=n,2!==t[s.place++])throw new Error("Signature DER invalid");const o=i(t,s);if(t.length!==o+s.place)throw new Error("Invalid R-length in signature DER");let c=t.slice(s.place,o+s.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 ge(new r(a),new r(c))}static fromCompact(t,e){if(65!==(t=Ct(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 ge(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 s=new r(U(t,i),16);return Ee(s,this,e)}toString(t){return this.toDER(t)}toDER(t){const e=(t,e)=>{if(!(e<128))throw new Error("len must be < 0x80");t.push(e)},i=t=>{let e=0;const i=t.length-1;for(;0===t[e]&&!(128&t[e+1])&&e<i;)e++;return 0===e?t:t.slice(e)};let r=this.r.toArray(),s=this.s.toArray();for(128&r[0]&&(r=[0].concat(r)),128&s[0]&&(s=[0].concat(s)),r=i(r),s=i(s);0===s[0]&&!(128&s[1]);)s=s.slice(1);let n=[2];e(n,r.length),n=n.concat(r),n.push(2),e(n,s.length);const a=n.concat(s);let o=[48];return e(o,a.length),o=o.concat(a),"hex"===t?Tt(o):"base64"===t?Dt(o):o}toCompact(t,e,i){if(t<0||t>3)throw new Error("Invalid recovery param");if("boolean"!=typeof e)throw new Error("Invalid compressed param");let r=27+t;e&&(r+=4);let s=[r];return s=s.concat(this.r.toArray("be",32)),s=s.concat(this.s.toArray("be",32)),"hex"===i?Tt(s):"base64"===i?Dt(s):s}RecoverPublicKey(t,e){const i=this.r,r=this.s,s=!!(1&t),n=t>>1,a=new be,o=a.n,c=a.g,h=0!==n?i.add(o):i,d=fe.fromX(h,s);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 _e(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 ye{K;V;constructor(t,e){if(t=Ct(t,"hex"),e=Ct(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 H(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(),Tt(i)}}function me(t,e,i=new be){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 we=new be,Ie=we.n.byteLength(),ve=we.n.subn(1),ke=Xt>>1n,Se=(t,e,i=!1,s)=>{t=me(t);const n=BigInt("0x"+t.toString(16)),a=BigInt("0x"+e.toString(16)),o=e.toArray("be",Ie),c=t.toArray("be",Ie),h=new ye(o,c);for(let t=0;;t++){let e="function"==typeof s?s(t):r.isBN(s)?s:new r(h.generate(Ie),16);if(null==e)throw new Error("k is undefined");if(e=me(e,!0),e.cmpn(1)<=0||e.cmp(ve)>=0){if(r.isBN(s))throw new Error("Invalid fixed custom K value (must be >1 and <N‑1)");continue}const o=BigInt("0x"+e.toString(16)),c=he(o,{x:re,y:se});if(0n===c.Z){if(r.isBN(s))throw new Error("Invalid fixed custom K value (k·G at infinity)");continue}const d=ee(c.Z),u=te(d,d),l=te(c.X,u),f=de(l);if(0n===f){if(r.isBN(s))throw new Error("Invalid fixed custom K value (r == 0)");continue}const p=le(o),b=ue(f,a),g=de(n+b);let y=ue(p,g);if(0n===y){if(r.isBN(s))throw new Error("Invalid fixed custom K value (s == 0)");continue}i&&y>ke&&(y=Xt-y);const m=new r(f.toString(16),16),w=new r(y.toString(16),16);return new ge(m,w)}},Ee=(t,e,i)=>{const r=BigInt("0x"+t.toString(16));if(null==i.x||null==i.y)throw new Error("Invalid public key: missing coordinates.");const s={x:BigInt("0x"+i.x.toString(16)),y:BigInt("0x"+i.y.toString(16))},n={r:BigInt("0x"+e.r.toString(16)),s:BigInt("0x"+e.s.toString(16))},{r:a,s:o}=n,c=r;if(a<=0n||a>=Xt||o<=0n||o>=Xt)return!1;const h=le(o);if(0n===h)return!1;const d=ue(c,h),u=ue(a,h),l=he(d,{x:re,y:se}),f=he(u,s),p=oe(l,f);if(0n===p.Z)return!1;const b=ee(p.Z),g=te(b,b),y=te(p.X,g);return de(y)===a};class _e extends fe{static fromPrivateKey(t){const e=(new be).g.mul(t);return new _e(e.x,e.y)}static fromString(t){const e=fe.fromString(t);return new _e(e.x,e.y)}static fromDER(t){const e=fe.fromDER(t);return new _e(e.x,e.y)}constructor(t,e=null,i=!0){if(t instanceof fe)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 s=new r(U(t,i),16);return Ee(s,e,this)}toDER(t){return"hex"===t?this.encode(!0,t):this.encode(!0)}toHash(t){const e=$(this.encode(!0));return"hex"===t?Tt(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 qt(this.toHash(),t)}deriveChild(t,e,i,s){let n;if("function"==typeof s){const e=s(t,this);void 0!==e?n=e:(n=this.deriveSharedSecret(t),"function"==typeof i&&i(t,this,n))}else n=this.deriveSharedSecret(t);const a=Ct(e,"utf8"),o=j(n.encode(!0),a),c=(new be).g.mul(new r(o)),h=this.add(c);return new _e(h.x,h.y)}static fromMsgHashAndCompactSignature(t,e,i){const s=Ct(e,i);if(65!==s.length)throw new Error("Invalid Compact Signature");const n=s[0];if(n<27||n>=35)throw new Error("Invalid Compact Byte");let a=s[0]-27;return a>3&&(a-=4),new ge(new r(s.slice(1,33)),new r(s.slice(33,65))).RecoverPublicKey(a,t)}}class Pe{_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 Oe=null;const xe=t=>(null==Oe&&(Oe=new Pe),Oe.generate(t));class Ne{x;y;constructor(t,e){const i=(new be).p;this.x=t.umod(i),this.y=e.umod(i)}toString(){return Ht(this.x.toArray())+"."+Ht(this.y.toArray())}static fromString(t){const[e,i]=t.split(".");return new Ne(new r(Vt(e)),new r(Vt(i)))}}class Ae{points;threshold;constructor(t,e){this.points=t,this.threshold=e??t.length}static fromPrivateKey(t,e){const i=(new be).p,s=[new Ne(new r(0),new r(t.toArray()))];for(let t=1;t<e;t++){const t=new r(xe(32)).umod(i),e=new r(xe(32)).umod(i);s.push(new Ne(t,e))}return new Ae(s)}valueAt(t){const e=(new be).p;let i=new r(0);for(let r=0;r<this.threshold;r++){let s=this.points[r].y;for(let i=0;i<this.threshold;i++)if(r!==i){const n=this.points[i].x,a=this.points[r].x,o=t.sub(n).umod(e),c=a.sub(n).umod(e).invm(e),h=o.mul(c).umod(e);s=s.mul(h).umod(e)}i=i.add(s).umod(e)}return i}}class Te{points;threshold;integrity;constructor(t,e,i){this.points=t,this.threshold=e,this.integrity=i}static fromBackupFormat(t){let e=0,i="";const r=t.map(((t,r)=>{const s=t.split(".");if(4!==s.length)throw new Error("Invalid share format in share "+r.toString()+'. Expected format: "x.y.t.i" - received '+t);const[n,a,o,c]=s;if(void 0===o)throw new Error("Threshold not found in share "+r.toString());if(void 0===c)throw new Error("Integrity not found in share "+r.toString());const h=parseInt(o);if(0!==r&&e!==h)throw new Error("Threshold mismatch in share "+r.toString());if(0!==r&&i!==c)throw new Error("Integrity mismatch in share "+r.toString());return e=h,i=c,Ne.fromString([n,a].join("."))}));return new Te(r,e,i)}toBackupFormat(){return this.points.map((t=>t.toString()+"."+this.threshold.toString()+"."+this.integrity))}}class Ce extends r{static fromRandom(){return new Ce(xe(32))}static fromString(t,e="hex"){return new Ce(super.fromString(t,e).toArray())}static fromHex(t){return new Ce(super.fromHex(t,"big"))}static fromWif(t,e=1){const i=Ut(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 Ce(i.data.slice(0,32))}constructor(t=0,e=10,i="be",s="apply"){if(t instanceof r?(super(),t.copy(this)):super(t,e,i),"nocheck"!==s){const t=this.checkInField();if(!t.inField){if("error"===s)throw new Error("Input is out of field");r.move(this,t.modN)}}}checkInField(){const t=new be,e=this.mod(t.n);return{inField:0===this.cmp(e),modN:e}}isValid(){return this.checkInField().inField}sign(t,e,i=!0,s){const n=new r(U(t,e),16);return Se(n,this,i,s)}verify(t,e,i){const s=new r(U(t,i),16);return Ee(s,e,this.toPublicKey())}toPublicKey(){const t=(new be).g.mul(this);return new _e(t.x,t.y)}toWif(t=[128]){if(!this.isValid())throw new Error("Value is out of field");return qt([...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,s){let n;if("function"==typeof s){const e=s(this,t);void 0!==e?n=e:(n=this.deriveSharedSecret(t),"function"==typeof i&&i(this,t,n))}else n=this.deriveSharedSecret(t);const a=Ct(e,"utf8"),o=j(n.encode(!0),a),c=new be;return new Ce(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=Ae.fromPrivateKey(this,t),s=[],n=new Set,a=new be,o=xe(64);for(let t=0;t<e;t++){let e,h=0;do{const i=(c=[t,h,...xe(32)],new q(o).update(c,undefined).digest());if(e=new r(i).umod(a.p),h++,h>5)throw new Error("Failed to generate unique x coordinate after 5 attempts")}while(e.isZero()||n.has(e.toString()));n.add(e.toString());const d=i.valueAt(e);s.push(new Ne(e,d))}var c;const h=this.toPublicKey().toHash("hex").slice(0,8);return new Te(s,t,h)}toBackupShares(t,e){return this.toKeyShares(t,e).toBackupFormat()}static fromBackupShares(t){return Ce.fromKeyShares(Te.fromBackupFormat(t))}static fromKeyShares(t){const{points:e,threshold:i,integrity:s}=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 n=new Ae(e,i),a=new Ce(n.valueAt(new r(0)).toArray());if(a.toPublicKey().toHash("hex").slice(0,8)!==s)throw new Error("Integrity hash mismatch");return a}}const Re=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]),Be=[[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))),Le=new Uint8Array(256),Me=new Uint8Array(256);for(let t=0;t<256;t++){const e=255&(t<<1^(128&t?27:0));Le[t]=e,Me[t]=e^t}function De(t,e,i){for(let r=0;r<4;r++){const s=e[i+r];for(let e=0;e<4;e++)t[e][r]^=s[e]}}function Fe(t){for(let e=0;e<4;e++)for(let i=0;i<4;i++)t[e][i]=Re[t[e][i]]}function Ve(t){for(let e=0;e<4;e++)t[e]=Re[t[e]]}function He(t){const e=t[0];t[0]=t[1],t[1]=t[2],t[2]=t[3],t[3]=e}function qe(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 Ue(t){for(let e=0;e<4;e++){const i=t[0][e],r=t[1][e],s=t[2][e],n=t[3][e];t[0][e]=Le[i]^Me[r]^s^n,t[1][e]=i^Le[r]^Me[s]^n,t[2][e]=i^r^Le[s]^Me[n],t[3][e]=Me[i]^r^s^Le[n]}}function Ke(t,e){let i,r,s,n;const a=[[],[],[],[]],o=[],c=Array.from(e);if(c.length<=16){for(;c.length<16;)c.unshift(0);n=11}else if(c.length<=24){for(;c.length<24;)c.unshift(0);n=13}else{if(!(e.length<=32))throw new Error("Illegal key length: "+String(e.length));for(;c.length<32;)c.unshift(0);n=15}const h=function(t,e){const i=e.length/4,r=[];for(let t=0;t<e.length;t++)t%4==0&&r.push([]),r[t>>2].push(e[t]);for(let e=i;e<4*t;e++){r[e]=[];const t=r[e-1].slice();if(e%i==0){He(t),Ve(t);const r=Be[e/i];for(let e=0;e<4;e++)t[e]^=r[e]}else i>6&&e%i==4&&Ve(t);for(let s=0;s<4;s++)r[e][s]=r[e-i][s]^t[s]}return r}(n,c);for(let e=0;e<4;e++)a[0][e]=t[4*e],a[1][e]=t[4*e+1],a[2][e]=t[4*e+2],a[3][e]=t[4*e+3];for(De(a,h,0),s=1;s<n;s++)Fe(a),qe(a),s+1<n&&Ue(a),De(a,h,4*s);for(i=0;i<4;i++)for(r=0;r<4;r++)o.push(a[r][i]);return o}const $e=function(t){return[(4278190080&t)>>>24,(16711680&t)>>16,(65280&t)>>8,255&t]},je=function(t){return new Array(t).fill(0)},ze=[225].concat(je(15)),We=function(t,e){for(let i=0;i<t.length;i++)t[i]^=e[i]},Ge=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},Xe=function(t,e){const i=e.slice(),r=je(16);for(let e=0;e<16;e++)for(let s=7;s>=0;s--)t[e]&1<<s&&We(r,i),1&i[15]?(Ge(i),We(i,ze)):Ge(i);return r},Je=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 Ye(t,e){let i=je(16);for(let r=0;r<t.length;r+=16){const s=i.slice();for(let e=0;e<16;e++)s[e]^=t[r+e]??0;i=Xe(s,e)}return i}function Ze(t,e,i){if(0===t.length)return[];const r=new Array(t.length);let s=e,n=0;const a=Math.ceil(t.length/16);for(let e=0;e<a;e++){const o=Ke(s,i),c=Math.min(16,t.length-n);for(let e=0;e<c;e++)r[n]=t[n]^o[e],n++;e+1<a&&(s=Je(s))}return r}class Qe extends r{static fromRandom(){return new Qe(xe(32))}encrypt(t,e){const i=xe(32);t=Ct(t,e);const{result:r,authenticationTag:s}=function(t,e,i,r){let s,n;const a=Ke(je(16),r);s=[...i],12===i.length?s=s.concat(je(3)).concat([1]):(i.length%16!=0&&(s=s.concat(je(16-i.length%16))),s=s.concat(je(8)),s=Ye(s.concat(je(4)).concat($e(8*i.length)),a));const o=Ze(t,Je(s),r);return n=e.slice(),0===e.length?n=n.concat(je(16)):e.length%16!=0&&(n=n.concat(je(16-e.length%16))),n=n.concat(o),0===o.length?n=n.concat(je(16)):o.length%16!=0&&(n=n.concat(je(16-o.length%16))),n=n.concat(je(4)).concat($e(8*e.length)).concat(je(4)).concat($e(8*o.length)),{result:o,authenticationTag:Ze(Ye(n,a),s,r)}}(t,[],i,this.toArray("be",32));return Mt([...i,...r,...s],e)}decrypt(t,e){const i=(t=Ct(t,e)).slice(0,32),r=t.slice(32),s=r.slice(-16),n=function(t,e,i,r,s){let n,a;const o=Ke(je(16),s);n=[...i],12===i.length?n=n.concat(je(3)).concat([1]):(i.length%16!=0&&(n=n.concat(je(16-i.length%16))),n=n.concat(je(8)),n=Ye(n.concat(je(4)).concat($e(8*i.length)),o));const c=Ze(t,Je(n),s);return a=e.slice(),0===e.length?a=a.concat(je(16)):e.length%16!=0&&(a=a.concat(je(16-e.length%16))),a=a.concat(t),0===t.length?a=a.concat(je(16)):t.length%16!=0&&(a=a.concat(je(16-t.length%16))),a=a.concat(je(4)).concat($e(8*e.length)).concat(je(4)).concat($e(8*t.length)),Ze(Ye(a,o),n,s).join()!==r.join()?null:c}(r.slice(0,-16),[],i,s,this.toArray());if(null===n)throw new Error("Decryption failed!");return Mt(n,e)}}class ti extends ge{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 Kt;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 s=r.satoshis??0;i.writeUInt64LE(s);const n=r.lockingScript?.toBinary()??[];i.writeVarIntNum(n.length),i.write(n)}const r=i.toArray();return K(r)}i.splice(t.inputIndex,0,e);let s=new Array(32).fill(0),n=new Array(32).fill(0),a=new Array(32).fill(0);t.scope&ti.SIGHASH_ANYONECANPAY||(s=(()=>{const t=new Kt;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(Ct(e.sourceTXID,"hex"));t.writeUInt32LE(e.sourceOutputIndex)}const e=t.toArray();return K(e)})()),t.scope&ti.SIGHASH_ANYONECANPAY||(31&t.scope)===ti.SIGHASH_SINGLE||(31&t.scope)===ti.SIGHASH_NONE||(n=(()=>{const t=new Kt;for(const e of i){const i=e.sequence??4294967295;t.writeUInt32LE(i)}const e=t.toArray();return K(e)})()),(31&t.scope)!==ti.SIGHASH_SINGLE&&(31&t.scope)!==ti.SIGHASH_NONE?a=r():(31&t.scope)===ti.SIGHASH_SINGLE&&t.inputIndex<t.outputs.length&&(a=r(t.inputIndex));const o=new Kt;o.writeInt32LE(t.transactionVersion),o.write(s),o.write(n),o.writeReverse(Ct(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 ti(t,e,1)}const e=t[t.length-1],i=t.slice(0,t.length-1),s=ge.fromDER(i);return new ti(s.r,s.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 ei{curve;constructor(){this.curve=new be}generateProof(t,e,i,r){const s=Ce.fromRandom(),n=s.toPublicKey(),a=i.mul(s),o=this.computeChallenge(e,i,r,a,n);return{R:n,SPrime:a,z:s.add(o.mul(t)).umod(this.curve.n)}}verifyProof(t,e,i,r){const{R:s,SPrime:n,z:a}=r,o=this.computeChallenge(t,e,i,n,s),c=this.curve.g.mul(a),h=s.add(t.mul(o));if(!c.eq(h))return!1;const d=e.mul(a),u=n.add(i.mul(o));return!!d.eq(u)}computeChallenge(t,e,i,s,n){const a=[...t.encode(!0),...e.encode(!0),...i.encode(!0),...s.encode(!0),...n.encode(!0)],o=U(a);return new r(o).umod(this.curve.n)}}const ii={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 ii)ii[ii[t]]=t;const ri=ii;class si{chunks;static fromASM(t){const e=[],i=t.split(" ");let r=0;for(;r<i.length;){const t=i[r];let s,n=0;if(t.startsWith("OP_")&&void 0!==ri[t]&&(s=t,n=ri[t]),"0"===t)n=0,e.push({op:n}),r+=1;else if("-1"===t)n=ri.OP_1NEGATE,e.push({op:n}),r+=1;else if(void 0===s){let t=i[r];t.length%2!=0&&(t="0"+t);const s=Ct(t,"hex");if(Mt(s,"hex")!==t)throw new Error("invalid hex string in script");const a=s.length;a>=0&&a<ri.OP_PUSHDATA1?n=a:a<Math.pow(2,8)?n=ri.OP_PUSHDATA1:a<Math.pow(2,16)?n=ri.OP_PUSHDATA2:a<Math.pow(2,32)&&(n=ri.OP_PUSHDATA4),e.push({data:s,op:n}),r+=1}else n===ri.OP_PUSHDATA1||n===ri.OP_PUSHDATA2||n===ri.OP_PUSHDATA4?(e.push({data:Ct(i[r+2],"hex"),op:n}),r+=3):(e.push({op:n}),r+=1)}return new si(e)}static fromHex(t){if(0===t.length)return si.fromBinary([]);if(t.length%2!=0)throw new Error("There is an uneven number of characters in the string which suggests it is not hex encoded.");if(!/^[0-9a-fA-F]+$/.test(t))throw new Error("Some elements in this string are not hex encoded.");return si.fromBinary(Ct(t,"hex"))}static fromBinary(t){t=[...t];const e=[];let i=0;const r=new $t(t);for(;!r.eof();){const t=r.readUInt8();if(t===ri.OP_RETURN&&0===i){e.push({op:t,data:r.read()});break}t===ri.OP_IF||t===ri.OP_NOTIF||t===ri.OP_VERIF||t===ri.OP_VERNOTIF?i++:t===ri.OP_ENDIF&&i--;let s=0,n=[];if(t>0&&t<ri.OP_PUSHDATA1)s=t,e.push({data:r.read(s),op:t});else if(t===ri.OP_PUSHDATA1){try{s=r.readUInt8(),n=r.read(s)}catch{r.read()}e.push({data:n,op:t})}else if(t===ri.OP_PUSHDATA2){try{s=r.readUInt16LE(),n=r.read(s)}catch{r.read()}e.push({data:n,op:t})}else if(t===ri.OP_PUSHDATA4){try{s=r.readUInt32LE(),n=r.read(s)}catch{r.read()}e.push({data:n,op:t})}else e.push({op:t})}return new si(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 Mt(this.toBinary(),"hex")}toBinary(){const t=new Kt;for(let e=0;e<this.chunks.length;e++){const i=this.chunks[e],r=i.op;if(t.writeUInt8(r),r===ri.OP_RETURN&&null!=i.data){t.write(i.data);break}null!=i.data&&(r<ri.OP_PUSHDATA1?t.write(i.data):r===ri.OP_PUSHDATA1?(t.writeUInt8(i.data.length),t.write(i.data)):r===ri.OP_PUSHDATA2?(t.writeUInt16LE(i.data.length),t.write(i.data)):r===ri.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)===ri.OP_0)this.chunks.push({op:ri.OP_0});else if(0===t.cmpn(-1))this.chunks.push({op:ri.OP_1NEGATE});else if(t.cmpn(1)>=0&&t.cmpn(16)<=0)this.chunks.push({op:t.toNumber()+ri.OP_1-1});else{const e=t.toSm("little");this.writeBin(e)}return this}writeBin(t){let e;const i=t.length>0?t:void 0;if(t.length>0&&t.length<ri.OP_PUSHDATA1)e=t.length;else if(0===t.length)e=ri.OP_0;else if(t.length<Math.pow(2,8))e=ri.OP_PUSHDATA1;else if(t.length<Math.pow(2,16))e=ri.OP_PUSHDATA2;else{if(!(t.length<Math.pow(2,32)))throw new Error("You can't push that much data");e=ri.OP_PUSHDATA4}return this.chunks.push({data:i,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!==ri.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 si([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>ri.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} ${ri[e]}`:`${i} ${Tt(t.data)}`,i}}class ni extends si{isLockingScript(){return!0}isUnlockingScript(){return!1}}class ai extends si{isLockingScript(){return!1}isUnlockingScript(){return!0}}class oi extends Error{txid;outputIndex;context;programCounter;stackState;altStackState;ifStackState;stackMem;altStackMem;constructor(t){const e=t.stackState.map((t=>null!=t&&void 0!==t.length?Tt(t):null==t?"null/undef":"INVALID_STACK_ITEM")).join(", "),i=t.altStackState.map((t=>null!=t&&void 0!==t.length?Tt(t):null==t?"null/undef":"INVALID_STACK_ITEM")).join(", "),r=`Context: ${t.context}, PC: ${t.programCounter}`,s=`Stack: [${e}] (len: ${t.stackState.length}, mem: ${t.stackMem})`,n=`AltStack: [${i}] (len: ${t.altStackState.length}, mem: ${t.altStackMem})`,a=`IfStack: [${t.ifStackState.join(", ")}]`;super(`Script evaluation error: ${t.message}\nTXID: ${t.txid}, OutputIdx: ${t.outputIndex}\n${r}\n${s}\n${n}\n${a}`),this.name=this.constructor.name,this.txid=t.txid,this.outputIndex=t.outputIndex,this.context=t.context,this.programCounter=t.programCounter,this.stackState=t.stackState.map((t=>t.slice())),this.altStackState=t.altStackState.map((t=>t.slice())),this.ifStackState=t.ifStackState.slice(),this.stackMem=t.stackMem,this.altStackMem=t.altStackMem}}const ci=1073741824,hi=Math.pow(2,31)-1,di=!0,ui=Object.freeze(new r(-1).toScriptNum()),li=Object.freeze(Array.from({length:17},((t,e)=>Object.freeze(new r(e).toScriptNum()))));class fi{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,s=t[r],n=t[r+1];if(2!==s)return!1;if(0===n)return!1;if(128&t[4])return!1;if(i>1&&0===t[4]&&!(128&t[5]))return!1;const a=r+2;return!(128&t[a]||n>1&&0===t[a]&&!(128&t[a+1])||i+n+7!==t.length)}(t))return this.scriptEvaluationError("The signature format is invalid."),!1;try{const e=ti.fromChecksigFormat(t);if(!e.hasLowS())return this.scriptEvaluationError("The signature must have a low S value."),!1;if(!(e.scope&ti.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{_e.fromDER(t)}catch(t){return this.scriptEvaluationError("The public key is in an unknown format."),!1}return!0}verifySignature(t,e,i){const s=ti.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}),n=new r(K(s));return Ee(n,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>ci&&this.scriptEvaluationError(`Data push > 1073741824 bytes (pc=${this.programCounter}).`);const s=!this.ifStack.includes(!1);var n,a;if(s&&((n=i)===ri.OP_2MUL||n===ri.OP_2DIV||n===ri.OP_VERIF||n===ri.OP_VERNOTIF||n===ri.OP_VER)&&this.scriptEvaluationError(`This opcode is currently disabled. (Opcode: ${ri[i]}, PC: ${this.programCounter})`),s&&i>=0&&i<=ri.OP_PUSHDATA4)(function(t){const e=t.data,i=t.op;return!(Array.isArray(e)&&(0===e.length?i!==ri.OP_0:1===e.length&&e[0]>=1&&e[0]<=16?i!==ri.OP_1+(e[0]-1):1===e.length&&129===e[0]?i!==ri.OP_1NEGATE:e.length<=75?i!==e.length:e.length<=255?i!==ri.OP_PUSHDATA1:e.length<=65535&&i!==ri.OP_PUSHDATA2))})(e)||this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`),this.pushStack(Array.isArray(e.data)?e.data:[]);else if(s||i>=ri.OP_IF&&i<=ri.OP_ENDIF){let t,e,n,o,c,h,d,u,l,f,p,b,g,y,m,w,I,v,k,S,E,_,P,O,x,N;switch(i){case ri.OP_1NEGATE:this.pushStackCopy(ui);break;case ri.OP_0:this.pushStackCopy(li[0]);break;case ri.OP_1:case ri.OP_2:case ri.OP_3:case ri.OP_4:case ri.OP_5:case ri.OP_6:case ri.OP_7:case ri.OP_8:case ri.OP_9:case ri.OP_10:case ri.OP_11:case ri.OP_12:case ri.OP_13:case ri.OP_14:case ri.OP_15:case ri.OP_16:b=i-(ri.OP_1-1),this.pushStackCopy(li[b]);break;case ri.OP_NOP:case ri.OP_NOP2:case ri.OP_NOP3:case ri.OP_NOP1:case ri.OP_NOP4:case ri.OP_NOP5:case ri.OP_NOP6:case ri.OP_NOP7:case ri.OP_NOP8:case ri.OP_NOP9:case ri.OP_NOP10:case ri.OP_NOP11:case ri.OP_NOP12:case ri.OP_NOP13:case ri.OP_NOP14:case ri.OP_NOP15:case ri.OP_NOP16:case ri.OP_NOP17:case ri.OP_NOP18:case ri.OP_NOP19:case ri.OP_NOP20:case ri.OP_NOP21:case ri.OP_NOP22:case ri.OP_NOP23:case ri.OP_NOP24:case ri.OP_NOP25:case ri.OP_NOP26:case ri.OP_NOP27:case ri.OP_NOP28:case ri.OP_NOP29:case ri.OP_NOP30:case ri.OP_NOP31:case ri.OP_NOP32:case ri.OP_NOP33:case ri.OP_NOP34:case ri.OP_NOP35:case ri.OP_NOP36:case ri.OP_NOP37:case ri.OP_NOP38:case ri.OP_NOP39:case ri.OP_NOP40:case ri.OP_NOP41:case ri.OP_NOP42:case ri.OP_NOP43:case ri.OP_NOP44:case ri.OP_NOP45:case ri.OP_NOP46:case ri.OP_NOP47:case ri.OP_NOP48:case ri.OP_NOP49:case ri.OP_NOP50:case ri.OP_NOP51:case ri.OP_NOP52:case ri.OP_NOP53:case ri.OP_NOP54:case ri.OP_NOP55:case ri.OP_NOP56:case ri.OP_NOP57:case ri.OP_NOP58:case ri.OP_NOP59:case ri.OP_NOP60:case ri.OP_NOP61:case ri.OP_NOP62:case ri.OP_NOP63:case ri.OP_NOP64:case ri.OP_NOP65:case ri.OP_NOP66:case ri.OP_NOP67:case ri.OP_NOP68:case ri.OP_NOP69:case ri.OP_NOP70:case ri.OP_NOP71:case ri.OP_NOP72:case ri.OP_NOP73:case ri.OP_NOP77:break;case ri.OP_IF:case ri.OP_NOTIF:y=!1,s&&(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===ri.OP_NOTIF&&(y=!y)),this.ifStack.push(y);break;case ri.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 ri.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop();break;case ri.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 ri.OP_RETURN:"UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.ifStack=[],this.programCounter--;break;case ri.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 ri.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 ri.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 ri.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),e=this.stackTop(-2),n=this.stackTop(-1),this.pushStackCopy(e),this.pushStackCopy(n);break;case ri.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),e=this.stackTop(-3),n=this.stackTop(-2),o=this.stackTop(-1),this.pushStackCopy(e),this.pushStackCopy(n),this.pushStackCopy(o);break;case ri.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),e=this.stackTop(-4),n=this.stackTop(-3),this.pushStackCopy(e),this.pushStackCopy(n);break;case ri.OP_2ROT:{this.stack.length<6&&this.scriptEvaluationError("OP_2ROT requires at least six items to be on the stack.");const t=this.popStack(),e=this.popStack(),i=this.popStack(),r=this.popStack(),s=this.popStack(),n=this.popStack();this.pushStack(r),this.pushStack(i),this.pushStack(e),this.pushStack(t),this.pushStack(n),this.pushStack(s);break}case ri.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 ri.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 ri.OP_DEPTH:this.pushStack(new r(this.stack.length).toScriptNum());break;case ri.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),this.popStack();break;case ri.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 ri.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),n=this.popStack(),this.popStack(),this.pushStack(n);break;case ri.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 ri.OP_PICK:case ri.OP_ROLL:{this.stack.length<2&&this.scriptEvaluationError(`${ri[i]} requires at least two items to be on the stack.`),u=r.fromScriptNum(this.popStack(),di),b=u.toNumber(),(b<0||b>=this.stack.length)&&this.scriptEvaluationError(`${ri[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===ri.OP_ROLL?(this.stack.splice(this.stack.length-1-b,1),this.stackMem-=t.length,this.pushStack(t)):this.pushStackCopy(t);break}case ri.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 ri.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 ri.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 ri.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 ri.OP_AND:case ri.OP_OR:case ri.OP_XOR:{this.stack.length<2&&this.scriptEvaluationError(`${ri[i]} requires at least two items on the stack.`),n=this.popStack(),e=this.popStack(),e.length!==n.length&&this.scriptEvaluationError(`${ri[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===ri.OP_AND?t[r]=e[r]&n[r]:i===ri.OP_OR?t[r]=e[r]|n[r]:t[r]=e[r]^n[r];this.pushStack(t);break}case ri.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 ri.OP_LSHIFT:case ri.OP_RSHIFT:{if(this.stack.length<2&&this.scriptEvaluationError(`${ri[i]} requires at least two items to be on the stack.`),f=r.fromScriptNum(this.popStack(),di),e=this.popStack(),b=f.toNumber(),b<0&&this.scriptEvaluationError(`${ri[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===ri.OP_LSHIFT?l.ushln(b):l.ushrn(b);const s=t.toArray("le",e.length);this.pushStack(s);break}case ri.OP_EQUAL:case ri.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${ri[i]} requires at least two items to be on the stack.`),n=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,n),this.pushStack(y?[1]:[]),i===ri.OP_EQUALVERIFY&&(y||this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."),this.popStack());break;case ri.OP_1ADD:case ri.OP_1SUB:case ri.OP_NEGATE:case ri.OP_ABS:case ri.OP_NOT:case ri.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${ri[i]} requires at least one item to be on the stack.`),u=r.fromScriptNum(this.popStack(),di),i){case ri.OP_1ADD:u=u.add(new r(1));break;case ri.OP_1SUB:u=u.sub(new r(1));break;case ri.OP_NEGATE:u=u.neg();break;case ri.OP_ABS:u.isNeg()&&(u=u.neg());break;case ri.OP_NOT:u=new r(0===u.cmpn(0)?1:0);break;case ri.OP_0NOTEQUAL:u=new r(0!==u.cmpn(0)?1:0)}this.pushStack(u.toScriptNum());break;case ri.OP_ADD:case ri.OP_SUB:case ri.OP_MUL:case ri.OP_DIV:case ri.OP_MOD:case ri.OP_BOOLAND:case ri.OP_BOOLOR:case ri.OP_NUMEQUAL:case ri.OP_NUMEQUALVERIFY:case ri.OP_NUMNOTEQUAL:case ri.OP_LESSTHAN:case ri.OP_GREATERTHAN:case ri.OP_LESSTHANOREQUAL:case ri.OP_GREATERTHANOREQUAL:case ri.OP_MIN:case ri.OP_MAX:{this.stack.length<2&&this.scriptEvaluationError(`${ri[i]} requires at least two items to be on the stack.`),n=this.popStack(),e=this.popStack(),f=r.fromScriptNum(n,di),l=r.fromScriptNum(e,di);let t=0;switch(i){case ri.OP_MUL:t=l.byteLength()+f.byteLength();break;case ri.OP_ADD:case ri.OP_SUB:t=Math.max(l.byteLength(),f.byteLength())+1;break;default:t=Math.max(l.byteLength(),f.byteLength())}this.ensureStackMem(t);let s=new r(0);switch(i){case ri.OP_ADD:s=l.add(f);break;case ri.OP_SUB:s=l.sub(f);break;case ri.OP_MUL:s=l.mul(f);break;case ri.OP_DIV:0===f.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),s=l.div(f);break;case ri.OP_MOD:0===f.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),s=l.mod(f);break;case ri.OP_BOOLAND:s=new r(0!==l.cmpn(0)&&0!==f.cmpn(0)?1:0);break;case ri.OP_BOOLOR:s=new r(0!==l.cmpn(0)||0!==f.cmpn(0)?1:0);break;case ri.OP_NUMEQUAL:case ri.OP_NUMEQUALVERIFY:s=new r(0===l.cmp(f)?1:0);break;case ri.OP_NUMNOTEQUAL:s=new r(0!==l.cmp(f)?1:0);break;case ri.OP_LESSTHAN:s=new r(l.cmp(f)<0?1:0);break;case ri.OP_GREATERTHAN:s=new r(l.cmp(f)>0?1:0);break;case ri.OP_LESSTHANOREQUAL:s=new r(l.cmp(f)<=0?1:0);break;case ri.OP_GREATERTHANOREQUAL:s=new r(l.cmp(f)>=0?1:0);break;case ri.OP_MIN:s=l.cmp(f)<0?l:f;break;case ri.OP_MAX:s=l.cmp(f)>0?l:f}this.pushStack(s.toScriptNum()),i===ri.OP_NUMEQUALVERIFY&&(this.castToBool(this.stackTop())||this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."),this.popStack());break}case ri.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(),di),f=r.fromScriptNum(this.popStack(),di),l=r.fromScriptNum(this.popStack(),di),y=l.cmp(f)>=0&&l.cmp(p)<0,this.pushStack(y?[1]:[]);break;case ri.OP_RIPEMD160:case ri.OP_SHA1:case ri.OP_SHA256:case ri.OP_HASH160:case ri.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${ri[i]} requires at least one item to be on the stack.`),t=this.popStack();let e=[];i===ri.OP_RIPEMD160?(a=t,e=(new D).update(a,undefined).digest()):i===ri.OP_SHA1?e=(t=>(new V).update(t,void 0).digest())(t):i===ri.OP_SHA256?e=U(t):i===ri.OP_HASH160?e=$(t):i===ri.OP_HASH256&&(e=K(t)),this.pushStack(e);break}case ri.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case ri.OP_CHECKSIG:case ri.OP_CHECKSIGVERIFY:{this.stack.length<2&&this.scriptEvaluationError(`${ri[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(`${ri[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 si(t),w.findAndDelete((new si).writeBin(I)),m=!1,I.length>0)try{k=ti.fromChecksigFormat(I),S=_e.fromDER(v),m=this.verifySignature(k,S,w)}catch(t){m=!1}this.pushStack(m?[1]:[]),i===ri.OP_CHECKSIGVERIFY&&(m||this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."),this.popStack());break}case ri.OP_CHECKMULTISIG:case ri.OP_CHECKMULTISIGVERIFY:{E=1,this.stack.length<E&&this.scriptEvaluationError(`${ri[i]} requires at least 1 item for nKeys.`),O=r.fromScriptNum(this.stackTop(-E),di).toNumber(),(O<0||O>hi)&&this.scriptEvaluationError(`${ri[i]} requires a key count between 0 and ${hi}.`),_=++E,E+=O,this.stack.length<E&&this.scriptEvaluationError(`${ri[i]} stack too small for nKeys and keys. Need ${E}, have ${this.stack.length}.`),x=r.fromScriptNum(this.stackTop(-E),di).toNumber(),(x<0||x>O)&&this.scriptEvaluationError(`${ri[i]} requires the number of signatures to be no greater than the number of keys.`),P=++E,E+=x,this.stack.length<E&&this.scriptEvaluationError(`${ri[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 si(t);for(let t=0;t<x;t++)I=this.stackTop(-P-t),w.findAndDelete((new si).writeBin(I));for(m=!0;m&&x>0;){if(0===O){m=!1;break}if(I=this.stackTop(-P),v=this.stackTop(-_),this.checkSignatureEncoding(I)&&this.checkPublicKeyEncoding(v)||this.scriptEvaluationError(`${ri[i]} requires correct encoding for the public key and signature.`),N=!1,I.length>0)try{k=ti.fromChecksigFormat(I),S=_e.fromDER(v),N=this.verifySignature(k,S,w)}catch(t){N=!1}N&&(P++,x--),_++,O--,x>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(`${ri[i]} requires an extra item (dummy) to be on the stack.`),this.popStack().length>0&&this.scriptEvaluationError(`${ri[i]} requires the extra stack item (dummy) to be empty.`),this.pushStack(m?[1]:[]),i===ri.OP_CHECKMULTISIGVERIFY&&(m||this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),this.popStack());break}case ri.OP_CAT:{this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),n=this.popStack(),e=this.popStack();const t=e.concat(n);t.length>ci&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),this.pushStack(t);break}case ri.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,di).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 ri.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(),di).toNumber(),(g>ci||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=jt(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 ri.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=jt(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){throw new oi({message:t,txid:this.sourceTXID,outputIndex:this.sourceOutputIndex,context:this.context,programCounter:this.programCounter,stackState:this.stack,altStackState:this.altStack,ifStackState:this.ifStack,stackMem:this.stackMem,altStackMem:this.altStackMem})}}function pi(t){if(null==t)throw new Error("must have value");return t}class bi{lock(t){let e;if("string"==typeof t){const i=Ut(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 ni([{op:ri.OP_DUP},{op:ri.OP_HASH160},{op:e.length,data:e},{op:ri.OP_EQUALVERIFY},{op:ri.OP_CHECKSIG}])}unlock(t,e="all",i=!1,r,s){return{sign:async(n,a)=>{let o=ti.SIGHASH_FORKID;"all"===e&&(o|=ti.SIGHASH_ALL),"none"===e&&(o|=ti.SIGHASH_NONE),"single"===e&&(o|=ti.SIGHASH_SINGLE),i&&(o|=ti.SIGHASH_ANYONECANPAY);const c=n.inputs[a],h=n.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(s||=c.sourceTransaction?.outputs[c.sourceOutputIndex].lockingScript,null==s)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");const u=ti.format({sourceTXID:d,sourceOutputIndex:pi(c.sourceOutputIndex),sourceSatoshis:r,transactionVersion:n.version,otherInputs:h,inputIndex:a,outputs:n.outputs,inputSequence:pi(c.sequence),subscript:s,lockTime:n.lockTime,scope:o}),l=t.sign(U(u)),f=new ti(l.r,l.s,o).toChecksigFormat(),p=t.toPublicKey().encode(!0);return new ai([{op:f.length,data:f},{op:p.length,data:p}])},estimateLength:async()=>108}}}function gi(t){if(null==t)throw new Error("must have value");return t}class yi{wallet;originator;static decode(t){const e=_e.fromString(Tt(gi(t.chunks[0].data))),i=[];for(let e=2;e<t.chunks.length;e++){const r=t.chunks[e+1]?.op;let s=t.chunks[e].data??[];if(0===s.length&&(t.chunks[e].op>=80&&t.chunks[e].op<=95?s=[t.chunks[e].op-80]:0===t.chunks[e].op?s=[0]:79===t.chunks[e].op&&(s=[129])),i.push(s),r===ri.OP_DROP||r===ri.OP_2DROP)break}return{fields:i,lockingPublicKey:e}}constructor(t,e){this.wallet=t,this.originator=e}async lock(t,e,i,r,s=!1,n=!0,a="before"){const{publicKey:o}=await this.wallet.getPublicKey({protocolID:e,keyID:i,counterparty:r,forSelf:s},this.originator),c=[],h=[];if(c.push({op:o.length/2,data:Ct(o,"hex")}),c.push({op:ri.OP_CHECKSIG}),n){const s=t.reduce(((t,e)=>[...t,...e]),[]),{signature:n}=await this.wallet.createSignature({data:s,protocolID:e,keyID:i,counterparty:r},this.originator);t.push(n)}for(const e of t)h.push(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:ri.OP_2DROP}),u-=2;return 0!==u&&h.push({op:ri.OP_DROP}),new ni("before"===a?[...c,...h]:[...h,...c])}unlock(t,e,i,r="all",s=!1,n,a){return{sign:async(o,c)=>{let h=ti.SIGHASH_FORKID;"all"===r&&(h|=ti.SIGHASH_ALL),"none"===r&&(h|=ti.SIGHASH_NONE),"single"===r&&(h|=ti.SIGHASH_SINGLE),s&&(h|=ti.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(n||=d.sourceTransaction?.outputs[d.sourceOutputIndex].satoshis,null==n||void 0===n)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=ti.format({sourceTXID:l,sourceOutputIndex:gi(d.sourceOutputIndex),sourceSatoshis:n,transactionVersion:o.version,otherInputs:u,inputIndex:c,outputs:o.outputs,inputSequence:d.sequence??4294967295,subscript:a,lockTime:o.lockTime,scope:h}),p=U(f),{signature:b}=await this.wallet.createSignature({data:p,protocolID:t,keyID:e,counterparty:i},this.originator),g=ge.fromDER([...b]),y=new ti(g.r,g.s,h).toChecksigFormat();return new ai([{op:y.length,data:y}])},estimateLength:async()=>73}}}class mi{value;constructor(t){this.value=t}async computeFee(t){const e=t=>t>2**32?9:t>65536?5:t>253?3:1;let i=4;i+=e(t.inputs.length);for(let r=0;r<t.inputs.length;r++){const s=t.inputs[r];let n;if(i+=40,"object"==typeof s.unlockingScript)n=s.unlockingScript.toBinary().length;else{if("object"!=typeof s.unlockingScriptTemplate)throw new Error("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");n=await s.unlockingScriptTemplate.estimateLength(t,r)}i+=e(n),i+=n}i+=e(t.outputs.length);for(const r of t.outputs){i+=8;const t=r.lockingScript.toBinary().length;i+=e(t),i+=t}return i+=4,Math.ceil(i/1e3*this.value)}}class wi extends mi{static ARC_POLICY_URL="https://arc.gorillapool.io/v1/policy";static instance=null;cachedRate=null;cacheTimestamp=0;cacheValidityMs;constructor(t=3e5){super(100),this.cacheValidityMs=t}static getInstance(t=3e5){return wi.instance||(wi.instance=new wi(t)),wi.instance}async fetchFeeRate(){const t=Date.now();if(null!==this.cachedRate&&t-this.cacheTimestamp<this.cacheValidityMs)return this.cachedRate;try{const e=await fetch(wi.ARC_POLICY_URL);if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const i=await e.json();if(!i.policy?.miningFee||"number"!=typeof i.policy.miningFee.satoshis||"number"!=typeof i.policy.miningFee.bytes)throw new Error("Invalid policy response format");const r=i.policy.miningFee.satoshis/i.policy.miningFee.bytes*1e3;return this.cachedRate=r,this.cacheTimestamp=t,r}catch(t){return null!==this.cachedRate?(console.warn("Failed to fetch live fee rate, using cached value:",t),this.cachedRate):(console.warn("Failed to fetch live fee rate, using default 100 sat/kb:",t),100)}}async computeFee(t){const e=await this.fetchFeeRate();return this.value=e,super.computeFee(t)}}class Ii{https;constructor(t){this.https=t}async request(t,e){return await new Promise(((i,r)=>{const s=this.https.request(t,e,(t=>{let e="";t.on("data",(t=>{e+=t})),t.on("end",(()=>{const r=t.statusCode>=200&&t.statusCode<=299,s=t.headers["content-type"],n=""!==e&&"string"==typeof s&&s.startsWith("application/json")?JSON.parse(e):e;i({status:t.statusCode,statusText:t.statusMessage,ok:r,data:n})}))}));s.on("error",(t=>{r(t)})),null!==e.data&&void 0!==e.data&&s.write(JSON.stringify(e.data)),s.end()}))}}class vi{fetch;constructor(t){this.fetch=t}async request(t,e){const i={method:e.method,headers:e.headers,body:JSON.stringify(e.data)},r=await this.fetch(t,i),s=r.headers.get("Content-Type"),n=s?.startsWith("application/json")?await r.json():await r.text();return{ok:r.ok,status:r.status,statusText:r.statusText,data:n}}}function ki(){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 vi(window.fetch.bind(window));if("undefined"==typeof require)return t;try{const t=require("https");return new Ii(t)}catch(e){return t}}function Si(){return`ts-sdk-${Tt(xe(16))}`}class Ei{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(t,e){if(this.URL=t,"string"==typeof e)this.apiKey=e,this.httpClient=ki(),this.deploymentId=Si(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const t=e??{},{apiKey:i,deploymentId:r,httpClient:s,callbackToken:n,callbackUrl:a,headers:o}=t;this.apiKey=i,this.httpClient=s??ki(),this.deploymentId=r??Si(),this.callbackToken=n,this.callbackUrl=a,this.headers=o}}requestHeaders(){const t={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(null!=this.apiKey&&""!==this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),null!=this.callbackUrl&&""!==this.callbackUrl&&(t["X-CallbackUrl"]=this.callbackUrl),null!=this.callbackToken&&""!==this.callbackToken&&(t["X-CallbackToken"]=this.callbackToken),null!=this.headers)for(const e in this.headers)t[e]=this.headers[e];return t}async broadcast(t){let e;try{e=t.toHexEF()}catch(i){if("All inputs must have source transactions when serializing to EF format"!==i.message)throw i;e=t.toHex()}const i={method:"POST",headers:this.requestHeaders(),data:{rawTx:e}};try{const t=await this.httpClient.request(`${this.URL}/v1/tx`,i);if(t.ok){const{txid:e,extraInfo:i,txStatus:r,competingTxs:s}=t.data,n={status:"success",txid:e,message:`${r} ${i}`};return null!=s&&(n.competingTxs=s),n}{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 _i{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??ki(),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 Pi{blockHeight;path;static fromHex(t){return Pi.fromBinary(Ct(t,"hex"))}static fromReader(t,e=!0){const i=t.readVarIntNum(),r=t.readUInt8(),s=Array(r).fill(null).map((()=>[]));let n,a,o;for(let e=0;e<r;e++){for(o=t.readVarIntNum();o>0;){a=t.readVarIntNum(),n=t.readUInt8();const i={offset:a};1&n?i.duplicate=!0:(2&n&&(i.txid=!0),i.hash=Tt(t.read(32).reverse())),Array.isArray(s[e])&&0!==s[e].length||(s[e]=[]),s[e].push(i),o--}s[e].sort(((t,e)=>t.offset-e.offset))}return new Pi(i,s,e)}static fromBinary(t){const e=new $t(t);return Pi.fromReader(e)}static fromCoinbaseTxidAndHeight(t,e){return new Pi(e,[[{offset:0,hash:t,txid:!0}]])}constructor(t,e,i=!0){this.blockHeight=t,this.path=e;const r=Array(this.path.length).fill(0).map((()=>new Set));let s;this.path.forEach(((t,e)=>{if(0===t.length&&0===e)throw new Error(`Empty level at height: ${e}`);const s=new Set;t.forEach((t=>{if(s.has(t.offset))throw new Error(`Duplicate offset: ${t.offset}, at height: ${e}`);if(s.add(t.offset),0===e){if(!0!==t.duplicate)for(let e=1;e<this.path.length;e++)r[e].add(t.offset>>e^1)}else if(i&&!r[e].has(t.offset))throw new Error(`Invalid offset: ${t.offset}, at height: ${e}, with legal offsets: ${Array.from(r[e]).join(", ")}`)}))})),this.path[0].forEach(((t,e)=>{if(0===e&&(s=this.computeRoot(t.hash)),s!==this.computeRoot(t.hash))throw new Error("Mismatched roots")}))}toBinary(){const t=new Kt;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(Ct(e.hash,"hex").reverse())}}return t.toArray()}toHex(){return Tt(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=>Tt(K(Ct(t,"hex").reverse()).reverse());let r=t;if(1===this.path.length&&1===this.path[0].length)return r;for(let t=0;t<this.path.length;t++){this.path[t];const s=e>>t^1,n=this.findOrComputeLeaf(t,s);if("object"!=typeof n)throw new Error(`Missing hash for index ${e} at height ${t}`);r=!0===n.duplicate?i((r??"")+(r??"")):i(s%2!=0?(n.hash??"")+(r??""):(r??"")+(n.hash??""))}return r}findOrComputeLeaf(t,e){const i=t=>Tt(K(Ct(t,"hex").reverse()).reverse());let r=this.path[t].find((t=>t.offset===e));if(null!=r)return r;if(0===t)return;const s=t-1,n=e<<1,a=this.findOrComputeLeaf(s,n);if(null==a||null==a.hash||""===a.hash)return;const o=this.findOrComputeLeaf(s,n+1);if(null==o)return;let c;return c=!0===o.duplicate?i(a.hash+a.hash):i((o.hash??"")+(a.hash??"")),r={offset:e,hash:c},r}async verify(t,e){const i=this.computeRoot(t);if(0===this.indexOf(t)){const t=await e.currentHeight();if(this.blockHeight+100<t)return!1}return await e.isValidRootForHeight(i,this.blockHeight)}combine(t){if(this.blockHeight!==t.blockHeight)throw new Error("You cannot combine paths which do not have the same block height.");if(this.computeRoot()!==t.computeRoot())throw new Error("You cannot combine paths which do not have the same root.");const e=[];for(let i=0;i<this.path.length;i++){e.push([]);for(let t=0;t<this.path[i].length;t++)e[i].push(this.path[i][t]);for(let r=0;r<t.path[i].length;r++)if(void 0===e[i].find((e=>e.offset===t.path[i][r].offset)))e[i].push(t.path[i][r]);else if(void 0!==t.path[i][r]?.txid&&null!==t.path[i][r]?.txid){const s=e[i].find((e=>e.offset===t.path[i][r].offset));null!=s&&(s.txid=!0)}}this.path=e,this.trim()}trim(){const t=(t,e)=>{0!==e.length&&e.slice(-1)[0]===t||e.push(t)},e=(t,e)=>{for(let i=t.length;i>=0;i--){const r=this.path[e].findIndex((e=>e.offset===t[i]));r>=0&&this.path[e].splice(r,1)}},i=e=>{const i=[];for(const r of e)t(r>>1,i);return i};let r=[],s=[];for(let t=0;t<this.path.length;t++)this.path[t].sort(((t,e)=>t.offset-e.offset));for(let e=0;e<this.path[0].length;e++){const i=this.path[0][e];if(!0===i.txid)t(i.offset>>1,r);else{const r=i.offset%2==1,n=this.path[0][e+(r?-1:1)];void 0!==n.txid&&null!==n.txid&&n.txid||t(n.offset,s)}}e(s,0);for(let t=1;t<this.path.length;t++)s=r,r=i(r),e(s,t)}}class Oi{_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=Tt(K(this._rawTx)),this._txid;throw new Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=Li.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 Oi(t,e)}static fromRawTx(t,e){return new Oi(t,e)}static fromTxid(t,e){return new Oi(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===Ai?this.isTxidOnly?(i(Ci.TXID_ONLY),(()=>{if(null==this._txid)throw new Error("Transaction ID (_txid) is undefined");t.writeReverse(Ct(this._txid,"hex"))})()):void 0!==this.bumpIndex?(i(Ci.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex),r()):(i(Ci.RAWTX),r()):(r(),(()=>{void 0===this.bumpIndex?i(Ci.RAWTX):(i(Ci.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex))})())}static fromReader(t,e){let i,r,s;if(e===Ai){const e=t.readUInt8();e===Ci.TXID_ONLY?s=Oi.fromTxid(Tt(t.readReverse(32))):(e===Ci.RAWTX_AND_BUMP_INDEX&&(r=t.readVarIntNum()),i=Li.fromReader(t),s=Oi.fromTx(i,r))}else i=Li.fromReader(t),r=0!==t.readUInt8()?t.readVarIntNum():void 0,s=Oi.fromTx(i,r);return s}}function xi(t){if(null==t)throw new Error("Expected a valid value, but got undefined.");return t}const Ni=4022206465,Ai=4022206466,Ti=16843009;var Ci,Ri;!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"}(Ci||(Ci={}));class Bi{bumps=[];txs=[];version=Ai;atomicTxid=void 0;txidIndex=void 0;constructor(t=Ai){this.version=t}findTxid(t){return this.ensureTxidIndex().get(t)}ensureTxidIndex(){if(null==this.txidIndex){this.txidIndex=new Map;for(const t of this.txs)this.txidIndex.set(t.txid,t)}return this.txidIndex}deleteFromIndex(t){this.txidIndex?.delete(t)}addToIndex(t){this.txidIndex?.set(t.txid,t)}makeTxidOnly(t){const e=this.txs.findIndex((e=>e.txid===t));if(-1===e)return;let i=this.txs[e];return i.isTxidOnly||(this.deleteFromIndex(t),this.txs.splice(e,1),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(xi(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(xi(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 s of i.path[0])if(s.hash===r){t.bumpIndex=e,s.txid=!0;break}}return e}mergeRawTx(t,e){const i=new Oi(t,e);return this.removeExistingTxid(i.txid),this.txs.push(i),this.addToIndex(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 Oi(t,i);if(this.txs.push(r),this.addToIndex(r),this.tryToValidateBumpIndex(r),i=r.bumpIndex,void 0===i)for(const e of t.inputs)null!=e.sourceTransaction&&this.mergeTransaction(e.sourceTransaction);return r}removeExistingTxid(t){const e=this.txs.findIndex((e=>e.txid===t));e>=0&&(this.deleteFromIndex(t),this.txs.splice(e,1))}mergeTxidOnly(t){let e=this.findTxid(t);return null==e&&(e=new Oi(t),this.txs.push(e),this.addToIndex(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)?Bi.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 s=(t,i)=>{const r=t.computeRoot(i);return void 0!==e.roots[t.blockHeight]&&""!==e.roots[t.blockHeight]||(e.roots[t.blockHeight]=r),e.roots[t.blockHeight]===r};for(const t of this.bumps)for(const i of t.path[0])if(!0===i.txid&&"string"==typeof i.hash&&i.hash.length>0&&(r[i.hash]=!0,!s(t,i.hash)))return e;for(const t of this.txs)if(void 0!==t.bumpIndex&&null==this.bumps[t.bumpIndex].path[0].find((e=>e.hash===t.txid)))return e;for(const t of this.txs){for(const i of t.inputTxids)if(!r[i])return e;r[t.txid]=!0}return e.valid=!0,e}toWriter(t){t.writeUInt32LE(this.version),t.writeVarIntNum(this.bumps.length);for(const e of this.bumps)t.write(e.toBinary());t.writeVarIntNum(this.txs.length);for(const e of this.txs)e.toWriter(t,this.version)}toBinary(){this.sortTxs();const t=new Kt;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 Kt;return r.writeUInt32LE(Ti),r.writeReverse(Ct(t,"hex")),i.toWriter(r),r.toArray()}toHex(){return Tt(this.toBinary())}static fromReader(t){let e,i=t.readUInt32LE();if(i===Ti&&(e=Tt(t.readReverse(32)),i=t.readUInt32LE()),i!==Ni&&i!==Ai)throw new Error(`Serialized BEEF must start with 4022206465 or ${Ai} but starts with ${i}`);const r=new Bi(i),s=t.readVarIntNum();for(let e=0;e<s;e++){const e=Pi.fromReader(t,!1);r.bumps.push(e)}const n=t.readVarIntNum();for(let e=0;e<n;e++){const e=Oi.fromReader(t,i);r.txs.push(e)}return r.atomicTxid=e,r}static fromBinary(t){const e=new $t(t);return Bi.fromReader(e)}static fromString(t,e="hex"){const i=Ct(t,e),r=new $t(i);return Bi.fromReader(r)}tryToValidateBumpIndex(t){if(void 0!==t.bumpIndex)return!0;const e=t.txid;for(let i=0;i<this.bumps.length;i++){const r=this.bumps[i].path[0].findIndex((t=>t.hash===e));if(r>=0)return t.bumpIndex=i,this.bumps[i].path[0][r].txid=!0,!0}return!1}sortTxs(){const t={},e={};let i=[];const r=[],s=[];for(const n of this.txs)e[n.txid]=n,n.isValid=n.hasProof,n.isValid?(t[n.txid]=!0,r.push(n)):n.isTxidOnly&&0===n.inputTxids.length?(t[n.txid]=!0,s.push(n)):i.push(n);const n={},a=[],o=i;i=[];for(const t of o){let r=!1;for(const i of t.inputTxids)void 0===e[i]&&(n[i]=!0,r=!0);r?a.push(t):i.push(t)}for(;i.length>0;){const e=i;i=[];for(const s of e)s.inputTxids.every((e=>t[e]))?(t[s.txid]=!0,r.push(s)):i.push(s);if(e.length===i.length)break}const c=i;return this.txs=a.concat(c).concat(s).concat(r),{missingInputs:Object.keys(n),notValid:c.map((t=>t.txid)),valid:Object.keys(t),withMissingInputs:a.map((t=>t.txid)),txidOnly:s.map((t=>t.txid))}}clone(){const t=new Bi;return t.version=this.version,t.bumps=Array.from(this.bumps),t.txs=Array.from(this.txs),t.txidIndex=void 0,t}trimKnownTxids(t){for(let e=0;e<this.txs.length;){const i=this.txs[e];i.isTxidOnly&&t.includes(i.txid)?(this.deleteFromIndex(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 s=e.path[i-1].find((t=>t.offset===r.offset+1)),n=r.offset>>1;void 0!==s&&"string"==typeof s.hash&&e.path[i].every((t=>t.offset!==n))&&e.path[i].push({offset:n,hash:(t=s.hash+r.hash,Tt(K(Ct(t,"hex").reverse()).reverse()))})}var t}}class Li{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}=Li.fromAnyBeef(t,e);return i}static fromAtomicBEEF(t){const{tx:e,txid:i,beef:r}=Li.fromAnyBeef(t);if(i!==r.atomicTxid)throw null!=r.atomicTxid?new Error(`Transaction with TXID ${r.atomicTxid} not found in BEEF data.`):new Error("beef must conform to BRC-95 and must contain the subject txid.");return e}static fromAnyBeef(t,e){const i=Bi.fromBinary(t);if(i.txs.length<1)throw new Error("beef must include at least one transaction.");const r=e??i.atomicTxid??i.txs.slice(-1)[0].txid,s=i.findAtomicTransaction(r);if(null==s)throw null!=e?new Error(`Transaction with TXID ${r} not found in BEEF data.`):new Error("beef does not contain transaction for atomic txid.");return{tx:s,beef:i,txid:r}}static fromEF(t){const e=new $t(t),i=e.readUInt32LE();if("0000000000ef"!==Tt(e.read(6)))throw new Error("Invalid EF marker");const r=e.readVarIntNum(),s=[];for(let t=0;t<r;t++){const t=Tt(e.readReverse(32)),i=e.readUInt32LE(),r=e.readVarIntNum(),n=e.read(r),a=ai.fromBinary(n),o=e.readUInt32LE(),c=e.readUInt64LEBn().toNumber(),h=e.readVarIntNum(),d=e.read(h),u=ni.fromBinary(d),l=new Li(void 0,[],[],void 0);l.outputs=Array(i+1).fill(null),l.outputs[i]={satoshis:c,lockingScript:u},s.push({sourceTransaction:l,sourceTXID:t,sourceOutputIndex:i,unlockingScript:a,sequence:o})}const n=e.readVarIntNum(),a=[];for(let t=0;t<n;t++){const t=e.readUInt64LEBn().toNumber(),i=e.readVarIntNum(),r=e.read(i),s=ni.fromBinary(r);a.push({satoshis:t,lockingScript:s})}const o=e.readUInt32LE();return new Li(i,s,a,o)}static parseScriptOffsets(t){const e=new $t(t),i=[],r=[];e.pos+=4;const s=e.readVarIntNum();for(let t=0;t<s;t++){e.pos+=36;const r=e.readVarIntNum();i.push({vin:t,offset:e.pos,length:r}),e.pos+=r+4}const n=e.readVarIntNum();for(let t=0;t<n;t++){e.pos+=8;const i=e.readVarIntNum();r.push({vout:t,offset:e.pos,length:i}),e.pos+=i}return{inputs:i,outputs:r}}static fromReader(t){const e=t.readUInt32LE(),i=t.readVarIntNum(),r=[];for(let e=0;e<i;e++){const e=Tt(t.readReverse(32)),i=t.readUInt32LE(),s=t.readVarIntNum(),n=t.read(s),a=ai.fromBinary(n),o=t.readUInt32LE();r.push({sourceTXID:e,sourceOutputIndex:i,unlockingScript:a,sequence:o})}const s=t.readVarIntNum(),n=[];for(let e=0;e<s;e++){const e=t.readUInt64LEBn().toNumber(),i=t.readVarIntNum(),r=t.read(i),s=ni.fromBinary(r);n.push({satoshis:e,lockingScript:s})}const a=t.readUInt32LE();return new Li(e,r,n,a)}static fromBinary(t){const e=new $t(t);return Li.fromReader(e)}static fromHex(t){return Li.fromBinary(Ct(t,"hex"))}static fromHexEF(t){return Li.fromEF(Ct(t,"hex"))}static fromHexBEEF(t,e){return Li.fromBEEF(Ct(t,"hex"),e)}constructor(t=1,e=[],i=[],r=0,s=new Map,n){this.version=t,this.inputs=e,this.outputs=i,this.lockTime=r,this.metadata=s,this.merklePath=n}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 bi).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=wi.getInstance(),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 s=Array(e.length).fill(1);r-=e.length,i+=e.length;for(let t=0;t<e.length-1;t++){const e=this.benfordNumber(0,r);s[t]=s[t]+e,i+=e,r-=e}for(const t of this.outputs)!0===t.change&&(t.satoshis=s.shift());return i}distributeEqualChange(t,e){let i=0;const r=Math.floor(t/e.length);for(const t of e)i+=r,t.satoshis=r;return i}benfordNumber(t,e){const i=Math.floor(9*Math.random())+1;return Math.floor(t+(e-t)*Math.log10(1+1/i)/Math.log10(10))}getFee(){let t=0;for(const e of this.inputs){if("object"!=typeof e.sourceTransaction)throw new Error("Source transactions or sourceSatoshis are required for all inputs to calculate fee");t+=e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0}let e=0;for(const t of this.outputs)e+=t.satoshis??0;return t-e}async sign(){this.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 Ei(t?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",e)}()){return await t.broadcast(this)}toBinary(){const t=new Kt;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(Ct(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 Kt;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(Ct(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 Tt(this.toEF())}toHex(){return Tt(this.toBinary())}toHexBEEF(){return Tt(this.toBEEF())}toHexAtomicBEEF(){return Tt(this.toAtomicBEEF())}hash(t){let e;return null!=this.cachedHash?e=this.cachedHash:(e=K(this.toBinary()),this.cachedHash=e),"hex"===t?Tt(e):e}id(t){const e=[...this.hash()];return e.reverse(),"hex"===t?Tt(e):e}async verify(t=function(){return new _i}(),e,i){const r=new Set,s=[this];for(;s.length>0;){const n=s.shift(),a=n?.id("hex")??"";if(null!=a&&""!==a&&r.has(a))continue;if("object"==typeof n?.merklePath){if("scripts only"===t){null!=a&&r.add(a);continue}if(await n.merklePath.verify(a,t)){r.add(a);continue}throw new Error(`Invalid merkle path for transaction ${a}`)}if(void 0!==e){if(void 0===n)throw new Error("Transaction is undefined");const t=Li.fromEF(n.toEF());if(delete t.outputs[0].satoshis,t.outputs[0].change=!0,await t.fee(e),n.getFee()<t.getFee())throw new Error(`Verification failed because the transaction ${a} has an insufficient fee and has not been mined.`)}let o=0;if(void 0===n)throw new Error("Transaction is undefined");for(let t=0;t<n.inputs.length;t++){const e=n.inputs[t];if("object"!=typeof e.sourceTransaction)throw new Error(`Verification failed because the input at index ${t} of transaction ${a} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if("object"!=typeof e.unlockingScript)throw new Error(`Verification failed because the input at index ${t} of transaction ${a} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);const c=e.sourceTransaction.outputs[e.sourceOutputIndex];o+=c.satoshis??0;const h=e.sourceTransaction.id("hex");r.has(h)||s.push(e.sourceTransaction);const d=n.inputs.filter(((e,i)=>i!==t));if(void 0===e.sourceTXID&&(e.sourceTXID=h),!new fi({sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:n.version,otherInputs:d,unlockingScript:e.unlockingScript,inputSequence:e.sequence??0,inputIndex:t,outputs:n.outputs,lockTime:n.lockTime,memoryLimit:i}).validate())return!1}let c=0;for(const t of n.outputs){if("number"!=typeof t.satoshis)throw new Error("Every output must have a defined amount during transaction verification.");c+=t.satoshis}if(c>o)return!1;r.add(a)}return!0}toBEEF(t){const e=new Kt;e.writeUInt32LE(Ni);const i=[],r=new Map,s=new Map,n=[],a=new Set,o=e=>{const c=e.id("hex");if(a.has(c))return;const h={tx:e},d=e.merklePath,u="object"==typeof d;if(u&&null!=d&&(h.pathIndex=(t=>{const e=r.get(t);if(void 0!==e)return e;const n=`${t.blockHeight}:${t.computeRoot()}`,a=s.get(n);if(void 0!==a)return i[a].combine(t),r.set(t,a),a;const o=i.length;return i.push(t),r.set(t,o),s.set(n,o),o})(d)),!u)for(let i=e.inputs.length-1;i>=0;i--){const r=e.inputs[i];if("object"==typeof r.sourceTransaction)o(r.sourceTransaction);else if(!1===t)throw new Error("A required source transaction is missing!")}a.add(c),n.push(h)};o(this),e.writeVarIntNum(i.length);for(const t of i)e.write(t.toBinary());e.writeVarIntNum(n.length);for(const t of n)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 Kt;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"}(Ri||(Ri={}));class Mi{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(t,e,i){this.cacheSharedSecret=e,this.retrieveCachedSharedSecret=i,this.anyone=new Ce(1).toPublicKey(),this.rootKey="anyone"===t?new Ce(1):t,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(t,e,i,r=!1){return i=this.normalizeCounterparty(i),r?this.rootKey.deriveChild(i,this.computeInvoiceNumber(t,e),this.cacheSharedSecret,this.retrieveCachedSharedSecret).toPublicKey():i.deriveChild(this.rootKey,this.computeInvoiceNumber(t,e),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}derivePrivateKey(t,e,i){return i=this.normalizeCounterparty(i),this.rootKey.deriveChild(i,this.computeInvoiceNumber(t,e),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}deriveSymmetricKey(t,e,i){i="anyone"===i?this.anyone:this.normalizeCounterparty(i);const r=this.derivePublicKey(t,e,i),s=this.derivePrivateKey(t,e,i);return new Qe(s.deriveSharedSecret(r)?.x?.toArray()??[])}revealCounterpartySecret(t){if("self"===t)throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");t=this.normalizeCounterparty(t);const e=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(e,"test").toHex()===this.rootKey.deriveChild(t,"test").toHex())throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(t).encode(!0)}revealSpecificSecret(t,e,i){t=this.normalizeCounterparty(t);const r=this.rootKey.deriveSharedSecret(t),s=Ct(this.computeInvoiceNumber(e,i),"utf8");return j(r.encode(!0),s)}normalizeCounterparty(t){if(null==t)throw new Error("counterparty must be self, anyone or a public key!");return"self"===t?this.rootKey.toPublicKey():"anyone"===t?new Ce(1).toPublicKey():"string"==typeof t?_e.fromString(t):t}computeInvoiceNumber(t,e){const i=t[0];if(!Number.isInteger(i)||i<0||i>2)throw new Error("Protocol security level must be 0, 1, or 2");const r=t[1].toLowerCase().trim();if(e.length>800)throw new Error("Key IDs must be 800 characters or less");if(e.length<1)throw new Error("Key IDs must be 1 character or more");if(r.length>400){if(!r.startsWith("specific linkage revelation "))throw new Error("Protocol names must be 400 characters or less");if(r.length>430)throw new Error("Specific linkage revelation protocol names must be 430 characters or less")}if(r.length<5)throw new Error("Protocol names must be 5 characters or more");if(r.includes(" "))throw new Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(r))throw new Error("Protocol names can only contain letters, numbers and spaces");if(r.endsWith(" protocol"))throw new Error('No need to end your protocol name with " protocol"');return`${i}-${r}-${e}`}}class Di{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(t,e){this.rootKey="anyone"===t?new Ce(1):t,this.keyDeriver=new Mi(this.rootKey,((t,e,i)=>{this.cacheSet(`${t.toString()}-${e.toString()}`,i)}),((t,e)=>this.cacheGet(`${t.toString()}-${e.toString()}`))),this.identityKey=this.rootKey.toPublicKey().toString(),this.cache=new Map;const i=e?.maxCacheSize;this.maxCacheSize=null!=i&&!isNaN(i)&&i>0?i:1e3}derivePublicKey(t,e,i,r=!1){const s=this.generateCacheKey("derivePublicKey",t,e,i,r);if(this.cache.has(s)){const t=this.cacheGet(s);if(void 0===t)throw new Error("Cached value is undefined");return t}{const n=this.keyDeriver.derivePublicKey(t,e,i,r);return this.cacheSet(s,n),n}}derivePrivateKey(t,e,i){const r=this.generateCacheKey("derivePrivateKey",t,e,i);if(this.cache.has(r)){const t=this.cacheGet(r);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.derivePrivateKey(t,e,i);return this.cacheSet(r,s),s}}deriveSymmetricKey(t,e,i){const r=this.generateCacheKey("deriveSymmetricKey",t,e,i);if(this.cache.has(r)){const t=this.cacheGet(r);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.deriveSymmetricKey(t,e,i);return this.cacheSet(r,s),s}}revealCounterpartySecret(t){const e=this.generateCacheKey("revealCounterpartySecret",t);if(this.cache.has(e)){const t=this.cacheGet(e);if(void 0===t)throw new Error("Cached value is undefined");return t}{const i=this.keyDeriver.revealCounterpartySecret(t);return this.cacheSet(e,i),i}}revealSpecificSecret(t,e,i){const r=this.generateCacheKey("revealSpecificSecret",t,e,i);if(this.cache.has(r)){const t=this.cacheGet(r);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.revealSpecificSecret(t,e,i);return this.cacheSet(r,s),s}}generateCacheKey(t,...e){return`${t}|${e.map((t=>this.serializeArgument(t))).join("|")}`}serializeArgument(t){return t instanceof _e||t instanceof Ce?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 Fi=class{keyDeriver;constructor(t){"string"!=typeof t.identityKey&&(t=new Di(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 ei).generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),_e.fromString(t.counterparty),fe.fromDER(i)),s=[...r.R.encode(!0),...r.SPrime.encode(!0),...r.z.toArray()],n=(new Date).toISOString(),{ciphertext:a}=await this.encrypt({plaintext:i,protocolID:[2,"counterparty linkage revelation"],keyID:n,counterparty:t.verifier}),{ciphertext:o}=await this.encrypt({plaintext:s,protocolID:[2,"counterparty linkage revelation"],keyID:n,counterparty:t.verifier});return{prover:e,verifier:t.verifier,counterparty:t.counterparty,revelationTime:n,encryptedLinkage:a,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(t){const{publicKey:e}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const i=this.keyDeriver.revealSpecificSecret(t.counterparty,t.protocolID,t.keyID),{ciphertext:r}=await this.encrypt({plaintext:i,protocolID:[2,`specific linkage revelation ${t.protocolID[0]} ${t.protocolID[1]}`],keyID:t.keyID,counterparty:t.verifier}),{ciphertext:s}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${t.protocolID[0]} ${t.protocolID[1]}`],keyID:t.keyID,counterparty:t.verifier});return{prover:e,verifier:t.verifier,counterparty:t.counterparty,protocolID:t.protocolID,keyID:t.keyID,encryptedLinkage:r,encryptedLinkageProof:s,proofType:0}}async encrypt(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self").encrypt(t.plaintext)}}async decrypt(t,e){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self").decrypt(t.ciphertext)}}async createHmac(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const e=this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self");return{hmac:j(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=j(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??U(t.data??[]),i=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePrivateKey(t.protocolID,t.keyID,t.counterparty??"anyone");return{signature:Se(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??U(t.data??[]),i=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePublicKey(t.protocolID,t.keyID,t.counterparty??"self",t.forSelf),s=Ee(new r(e),ge.fromDER(t.signature),i);if(!s){const t=new Error("Signature is not valid");throw t.code="ERR_INVALID_SIGNATURE",t}return{valid:s}}};class Vi{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 Hi 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 qi,Ui,Ki;!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"}(qi||(qi={}));class $i{domain;constructor(t="*"){if("object"!=typeof window)throw new Error("The XDM substrate requires a global window object.");if("function"!=typeof window.postMessage)throw new Error("The window object does not seem to support postMessage calls.");this.domain=t}async invoke(t,e){return await new Promise(((i,r)=>{const s=Dt(xe(12)),n=t=>{if("CWI"===t.data.type&&t.isTrusted&&t.data.id===s&&!0!==t.data.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",n),"error"===t.data.status){const e=new Hi(t.data.description,t.data.code);r(e)}else i(t.data.result)};window.addEventListener("message",n),window.parent.postMessage({type:"CWI",isInvocation:!0,id:s,call:t,args:e},this.domain)}))}async createAction(t){return await this.invoke("createAction",t)}async signAction(t){return await this.invoke("signAction",t)}async abortAction(t){return await this.invoke("abortAction",t)}async listActions(t){return await this.invoke("listActions",t)}async internalizeAction(t){return await this.invoke("internalizeAction",t)}async listOutputs(t){return await this.invoke("listOutputs",t)}async relinquishOutput(t){return await this.invoke("relinquishOutput",t)}async getPublicKey(t){return await this.invoke("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.invoke("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.invoke("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.invoke("encrypt",t)}async decrypt(t){return await this.invoke("decrypt",t)}async createHmac(t){return await this.invoke("createHmac",t)}async verifyHmac(t){return await this.invoke("verifyHmac",t)}async createSignature(t){return await this.invoke("createSignature",t)}async verifySignature(t){return await this.invoke("verifySignature",t)}async acquireCertificate(t){return await this.invoke("acquireCertificate",t)}async listCertificates(t){return await this.invoke("listCertificates",t)}async proveCertificate(t){return await this.invoke("proveCertificate",t)}async relinquishCertificate(t){return await this.invoke("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.invoke("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.invoke("discoverByAttributes",t)}async isAuthenticated(t){return await this.invoke("isAuthenticated",t)}async waitForAuthentication(t){return await this.invoke("waitForAuthentication",t)}async getHeight(t){return await this.invoke("getHeight",t)}async getHeaderForHeight(t){return await this.invoke("getHeaderForHeight",t)}async getNetwork(t){return await this.invoke("getNetwork",t)}async getVersion(t){return await this.invoke("getVersion",t)}}class ji{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(t,e,i,r,s,n,a){this.type=t,this.serialNumber=e,this.subject=i,this.certifier=r,this.revocationOutpoint=s,this.fields=n,this.signature=a}toBinary(t=!0){const e=new Kt,i=Ct(this.type,"base64");e.write(i);const r=Ct(this.serialNumber,"base64");e.write(r);const s=Ct(this.subject,"hex");e.write(s);const n=Ct(this.certifier,"hex");e.write(n);const[a,o]=this.revocationOutpoint.split("."),c=Ct(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=Ct(t,"utf8");e.writeVarIntNum(r.length),e.write(r);const s=Ct(i,"utf8");e.writeVarIntNum(s.length),e.write(s)}if(t&&(this.signature??"").length>0){const t=Ct(this.signature,"hex");e.write(t)}return e.toArray()}static fromBinary(t){const e=new $t(t),i=Dt(e.read(32)),r=Dt(e.read(32)),s=e.read(33),n=Tt(s),a=e.read(33),o=Tt(a),c=e.read(32),h=`${Tt(c)}.${e.readVarIntNum()}`,d=e.readVarIntNum(),u={};for(let t=0;t<d;t++){const t=e.readVarIntNum(),i=e.read(t),r=Lt(i),s=e.readVarIntNum(),n=e.read(s),a=Lt(n);u[r]=a}let l;if(!e.eof()){const t=e.read();l=ge.fromDER(t).toString("hex")}return new ji(i,r,n,o,h,u,l)}async verify(){const t=new Fi("anyone"),e=this.toBinary(!1),i=this.signature??"",{valid:r}=await t.verifySignature({signature:Ct(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=Tt(i)}static getCertificateFieldEncryptionDetails(t,e){return{protocolID:[2,"certificate field encryption"],keyID:e?`${e} ${t}`:t}}}(Ki=Ui||(Ui={}))[Ki.createAction=1]="createAction",Ki[Ki.signAction=2]="signAction",Ki[Ki.abortAction=3]="abortAction",Ki[Ki.listActions=4]="listActions",Ki[Ki.internalizeAction=5]="internalizeAction",Ki[Ki.listOutputs=6]="listOutputs",Ki[Ki.relinquishOutput=7]="relinquishOutput",Ki[Ki.getPublicKey=8]="getPublicKey",Ki[Ki.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",Ki[Ki.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",Ki[Ki.encrypt=11]="encrypt",Ki[Ki.decrypt=12]="decrypt",Ki[Ki.createHmac=13]="createHmac",Ki[Ki.verifyHmac=14]="verifyHmac",Ki[Ki.createSignature=15]="createSignature",Ki[Ki.verifySignature=16]="verifySignature",Ki[Ki.acquireCertificate=17]="acquireCertificate",Ki[Ki.listCertificates=18]="listCertificates",Ki[Ki.proveCertificate=19]="proveCertificate",Ki[Ki.relinquishCertificate=20]="relinquishCertificate",Ki[Ki.discoverByIdentityKey=21]="discoverByIdentityKey",Ki[Ki.discoverByAttributes=22]="discoverByAttributes",Ki[Ki.isAuthenticated=23]="isAuthenticated",Ki[Ki.waitForAuthentication=24]="waitForAuthentication",Ki[Ki.getHeight=25]="getHeight",Ki[Ki.getHeaderForHeight=26]="getHeaderForHeight",Ki[Ki.getNetwork=27]="getNetwork",Ki[Ki.getVersion=28]="getVersion";const zi=Ui;class Wi{wire;constructor(t){this.wire=t}async transmit(t,e="",i=[]){const r=new Kt;r.writeUInt8(zi[t]);const s=Ct(e,"utf8");r.writeUInt8(s.length),r.write(s),i.length>0&&r.write(i);const n=r.toArray(),a=await this.wire.transmitToWallet(n),o=new $t(a),c=o.readUInt8();if(0===c)return o.read();{const t=o.readVarIntNum(),e=o.read(t),i=Lt(e),r=o.readVarIntNum(),s=o.read(r),n=Lt(s);throw new Hi(i,c,n)}}async createAction(t,e){const i=new Kt,r=Ct(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=Ct(e.unlockingScript,"hex");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1),i.writeVarIntNum(e.unlockingScriptLength??0);const t=Ct(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=Ct(e.lockingScript,"hex");i.writeVarIntNum(t.length),i.write(t),i.writeVarIntNum(e.satoshis);const r=Ct(e.outputDescription,"utf8");if(i.writeVarIntNum(r.length),i.write(r),null!=e.basket&&""!==e.basket){const t=Ct(e.basket,"utf8");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1);if(null!=e.customInstructions&&""!==e.customInstructions){const t=Ct(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=Ct(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=Ct(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=Ct(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=Ct(e,"hex");i.write(t)}}else i.writeVarIntNum(-1);"boolean"==typeof t.options.randomizeOutputs?i.writeInt8(t.options.randomizeOutputs?1:0):i.writeInt8(-1)}else i.writeInt8(0);const s=await this.transmit("createAction",e,i.toArray()),n=new $t(s),a={};if(1===n.readInt8()){const t=n.read(32);a.txid=Tt(t)}if(1===n.readInt8()){const t=n.readVarIntNum();a.tx=n.read(t)}const o=n.readVarIntNum();if(o>=0){a.noSendChange=[];for(let t=0;t<o;t++){const t=this.readOutpoint(n);a.noSendChange.push(t)}}const c=n.readVarIntNum();if(c>=0){a.sendWithResults=[];for(let t=0;t<c;t++){const t=n.read(32),e=Tt(t),i=n.readInt8();let r="unproven";1===i?r="unproven":2===i?r="sending":3===i&&(r="failed"),a.sendWithResults.push({txid:e,status:r})}}if(1===n.readInt8()){const t=n.readVarIntNum(),e=n.read(t),i=n.readVarIntNum(),r=n.read(i);a.signableTransaction={tx:e,reference:Dt(r)}}return a}async signAction(t,e){const i=new Kt,r=Object.keys(t.spends);i.writeVarIntNum(r.length);for(const e of r){i.writeVarIntNum(Number(e));const r=t.spends[Number(e)],s=Ct(r.unlockingScript,"hex");i.writeVarIntNum(s.length),i.write(s),"number"==typeof r.sequenceNumber?i.writeVarIntNum(r.sequenceNumber):i.writeVarIntNum(-1)}const s=Ct(t.reference,"base64");if(i.writeVarIntNum(s.length),i.write(s),null!=t.options)if(i.writeInt8(1),"boolean"==typeof t.options.acceptDelayedBroadcast?i.writeInt8(t.options.acceptDelayedBroadcast?1:0):i.writeInt8(-1),"boolean"==typeof t.options.returnTXIDOnly?i.writeInt8(t.options.returnTXIDOnly?1:0):i.writeInt8(-1),"boolean"==typeof t.options.noSend?i.writeInt8(t.options.noSend?1:0):i.writeInt8(-1),null!=t.options.sendWith){i.writeVarIntNum(t.options.sendWith.length);for(const e of t.options.sendWith){const t=Ct(e,"hex");i.write(t)}}else i.writeVarIntNum(-1);else i.writeInt8(0);const n=await this.transmit("signAction",e,i.toArray()),a=new $t(n),o={};if(1===a.readInt8()){const t=a.read(32);o.txid=Tt(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=Tt(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,Ct(t.reference,"base64")),{aborted:!0}}async listActions(t,e){const i=new Kt;i.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Ct(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}"any"===t.labelQueryMode?i.writeInt8(1):"all"===t.labelQueryMode?i.writeInt8(2):i.writeInt8(-1);const r=[t.includeLabels,t.includeInputs,t.includeInputSourceLockingScripts,t.includeInputUnlockingScripts,t.includeOutputs,t.includeOutputLockingScripts];for(const t of r)"boolean"==typeof t?i.writeInt8(t?1:0):i.writeInt8(-1);"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const s=await this.transmit("listActions",e,i.toArray()),n=new $t(s),a=n.readVarIntNum(),o=[];for(let t=0;t<a;t++){const t=n.read(32),e=Tt(t),i=n.readVarIntNum(),r=n.readInt8();let s;switch(r){case 1:s="completed";break;case 2:s="unprocessed";break;case 3:s="sending";break;case 4:s="unproven";break;case 5:s="unsigned";break;case 6:s="nosend";break;case 7:s="nonfinal";break;case 8:s="failed";break;default:throw new Error(`Unknown status code: ${r}`)}const a=1===n.readInt8(),c=n.readVarIntNum(),h=n.read(c),d={txid:e,satoshis:i,status:s,isOutgoing:a,description:Lt(h),version:0,lockTime:0},u=n.readVarIntNum();if(u>=0){d.labels=[];for(let t=0;t<u;t++){const t=n.readVarIntNum(),e=n.read(t);d.labels.push(Lt(e))}}d.version=n.readVarIntNum(),d.lockTime=n.readVarIntNum();const l=n.readVarIntNum();if(l>=0){d.inputs=[];for(let t=0;t<l;t++){const t=this.readOutpoint(n),e=n.readVarIntNum(),i=n.readVarIntNum();let r;if(i>=0){const t=n.read(i);r=Tt(t)}const s=n.readVarIntNum();let a;if(s>=0){const t=n.read(s);a=Tt(t)}const o=n.readVarIntNum(),c=n.read(o),h=Lt(c),u=n.readVarIntNum();d.inputs.push({sourceOutpoint:t,sourceSatoshis:e,sourceLockingScript:r,unlockingScript:a,inputDescription:h,sequenceNumber:u})}}const f=n.readVarIntNum();if(f>=0){d.outputs=[];for(let t=0;t<f;t++){const t=n.readVarIntNum(),e=n.readVarIntNum(),i=n.readVarIntNum();let r;if(i>=0){const t=n.read(i);r=Tt(t)}const s=1===n.readInt8(),a=n.readVarIntNum(),o=n.read(a),c=Lt(o),h=n.readVarIntNum();let u;if(h>=0){const t=n.read(h);u=Lt(t)}const l=n.readVarIntNum(),f=[];if(l>=0)for(let t=0;t<l;t++){const t=n.readVarIntNum(),e=n.read(t);f.push(Lt(e))}const p=n.readVarIntNum();let b;if(p>=0){const t=n.read(p);b=Lt(t)}d.outputs.push({outputIndex:t,satoshis:e,lockingScript:r,spendable:s,outputDescription:c,basket:u,tags:f,customInstructions:b})}}o.push(d)}return{totalActions:a,actions:o}}async internalizeAction(t,e){const i=new Kt;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(Ct(e.paymentRemittance.senderIdentityKey,"hex"));const t=Ct(e.paymentRemittance.derivationPrefix,"base64");i.writeVarIntNum(t.length),i.write(t);const r=Ct(e.paymentRemittance.derivationSuffix,"base64");i.writeVarIntNum(r.length),i.write(r)}else{i.writeUInt8(2);const t=Ct(e.insertionRemittance?.basket,"utf8");if(i.writeVarIntNum(t.length),i.write(t),"string"==typeof e.insertionRemittance?.customInstructions&&""!==e.insertionRemittance.customInstructions){const t=Ct(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=Ct(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=Ct(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}}else i.writeVarIntNum(-1);const r=Ct(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 Kt,r=Ct(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=Ct(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}}else i.writeVarIntNum(0);"all"===t.tagQueryMode?i.writeInt8(1):"any"===t.tagQueryMode?i.writeInt8(2):i.writeInt8(-1),"locking scripts"===t.include?i.writeInt8(1):"entire transactions"===t.include?i.writeInt8(2):i.writeInt8(-1),"boolean"==typeof t.includeCustomInstructions?i.writeInt8(t.includeCustomInstructions?1:0):i.writeInt8(-1),"boolean"==typeof t.includeTags?i.writeInt8(t.includeTags?1:0):i.writeInt8(-1),"boolean"==typeof t.includeLabels?i.writeInt8(t.includeLabels?1:0):i.writeInt8(-1),"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const s=await this.transmit("listOutputs",e,i.toArray()),n=new $t(s),a=n.readVarIntNum(),o=n.readVarIntNum();let c;o>=0&&(c=n.read(o));const h=[];for(let t=0;t<a;t++){const t={spendable:!0,outpoint:this.readOutpoint(n),satoshis:n.readVarIntNum()},e=n.readVarIntNum();e>=0&&(t.lockingScript=Tt(n.read(e)));const i=n.readVarIntNum();i>=0&&(t.customInstructions=Lt(n.read(i)));const r=n.readVarIntNum();if(-1!==r){const e=[];for(let t=0;t<r;t++){const t=n.readVarIntNum();e.push(Lt(n.read(t)))}t.tags=e}const s=n.readVarIntNum();if(-1!==s){const e=[];for(let t=0;t<s;t++){const t=n.readVarIntNum();e.push(Lt(n.read(t)))}t.labels=e}h.push(t)}return{totalOutputs:a,BEEF:c,outputs:h}}async relinquishOutput(t,e){const i=new Kt,r=Ct(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 Kt,[i,r]=t.split(".");return e.write(Ct(i,"hex")),e.writeVarIntNum(Number(r)),e.toArray()}readOutpoint(t){return`${Tt(t.read(32))}.${t.readVarIntNum()}`}async getPublicKey(t,e){const i=new Kt;i.writeUInt8(t.identityKey?1:0),t.identityKey?i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)):(i.write(this.encodeKeyRelatedParams(t.protocolID??=[Ri.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:Tt(r)}}async revealCounterpartyKeyLinkage(t,e){const i=new Kt;i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),i.write(Ct(t.counterparty,"hex")),i.write(Ct(t.verifier,"hex"));const r=await this.transmit("revealCounterpartyKeyLinkage",e,i.toArray()),s=new $t(r),n=Tt(s.read(33)),a=Tt(s.read(33)),o=Tt(s.read(33)),c=s.readVarIntNum(),h=Lt(s.read(c)),d=s.readVarIntNum(),u=s.read(d),l=s.readVarIntNum();return{prover:n,verifier:a,counterparty:o,revelationTime:h,encryptedLinkage:u,encryptedLinkageProof:s.read(l)}}async revealSpecificKeyLinkage(t,e){const i=new Kt;i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.write(Ct(t.verifier,"hex"));const r=await this.transmit("revealSpecificKeyLinkage",e,i.toArray()),s=new $t(r),n=Tt(s.read(33)),a=Tt(s.read(33)),o=Tt(s.read(33)),c=s.readUInt8(),h=s.readVarIntNum(),d=Lt(s.read(h)),u=s.readVarIntNum(),l=Lt(s.read(u)),f=s.readVarIntNum(),p=s.read(f),b=s.readVarIntNum();return{prover:n,verifier:a,counterparty:o,protocolID:[c,d],keyID:l,encryptedLinkage:p,encryptedLinkageProof:s.read(b),proofType:s.readUInt8()}}async encrypt(t,e){const i=new Kt;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 Kt;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 Kt;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 Kt;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 Kt;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 Kt;return i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),"boolean"==typeof t.forSelf?i.writeInt8(t.forSelf?1:0):i.writeInt8(-1),i.writeVarIntNum(t.signature.length),i.write(t.signature),"object"==typeof t.data?(i.writeUInt8(1),i.writeVarIntNum(t.data.length),i.write(t.data)):(i.writeUInt8(2),i.write(t.hashToDirectlyVerify??[])),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),await this.transmit("verifySignature",e,i.toArray()),{valid:!0}}encodeKeyRelatedParams(t,e,i,r,s){const n=new Kt;n.writeUInt8(t[0]);const a=Ct(t[1],"utf8");n.writeVarIntNum(a.length),n.write(a);const o=Ct(e,"utf8");return n.writeVarIntNum(o.length),n.write(o),"string"!=typeof i?n.writeUInt8(0):"self"===i?n.writeUInt8(11):"anyone"===i?n.writeUInt8(12):n.write(Ct(i,"hex")),n.write(this.encodePrivilegedParams(r,s)),n.toArray()}async acquireCertificate(t,e){const i=new Kt;i.write(Ct(t.type,"base64")),i.write(Ct(t.certifier,"hex"));const r=Object.entries(t.fields);i.writeVarIntNum(r.length);for(const[t,e]of r){const r=Ct(t,"utf8"),s=Ct(e,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(s.length),i.write(s)}if(i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),i.writeUInt8("direct"===t.acquisitionProtocol?1:2),"direct"===t.acquisitionProtocol){i.write(Ct(t.serialNumber,"base64")),i.write(this.encodeOutpoint(t.revocationOutpoint??""));const e=Ct(t.signature,"hex");i.writeVarIntNum(e.length),i.write(e);const r="certifier"!==t.keyringRevealer?Ct(t.keyringRevealer,"hex"):[11];i.write(r);const s=Object.keys(t.keyringForSubject??{});i.writeVarIntNum(s.length);for(let e=0;e<s.length;e++){const r=Ct(s[e],"utf8");i.writeVarIntNum(r.length),i.write(r);const n=Ct(t.keyringForSubject?.[s[e]],"base64");i.writeVarIntNum(n.length),i.write(n)}}else{const e=Ct(t.certifierUrl,"utf8");i.writeVarIntNum(e.length),i.write(e)}const s=await this.transmit("acquireCertificate",e,i.toArray()),n=ji.fromBinary(s);return{...n,signature:n.signature}}encodePrivilegedParams(t,e){const i=new Kt;if("boolean"==typeof t?i.writeInt8(t?1:0):i.writeInt8(-1),"string"==typeof e){const t=Ct(e,"utf8");i.writeInt8(t.length),i.write(t)}else i.writeInt8(-1);return i.toArray()}async listCertificates(t,e){const i=new Kt;i.writeVarIntNum(t.certifiers.length);for(let e=0;e<t.certifiers.length;e++)i.write(Ct(t.certifiers[e],"hex"));i.writeVarIntNum(t.types.length);for(let e=0;e<t.types.length;e++)i.write(Ct(t.types[e],"base64"));"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason));const r=await this.transmit("listCertificates",e,i.toArray()),s=new $t(r),n=s.readVarIntNum(),a=[];for(let t=0;t<n;t++){const t=s.readVarIntNum(),e=s.read(t),i=ji.fromBinary(e),r={};if(1===s.readInt8()){const t=s.readVarIntNum();for(let e=0;e<t;e++){const t=s.readVarIntNum(),e=Lt(s.read(t)),i=s.readVarIntNum();r[e]=Dt(s.read(i))}}const n=s.readVarIntNum();let o;n>0&&(o=Lt(s.read(n))),a.push({...i,signature:i.signature,keyring:r,verifier:o})}return{totalCertificates:n,certificates:a}}async proveCertificate(t,e){const i=new Kt,r=Ct(t.certificate.type,"base64");i.write(r);const s=Ct(t.certificate.subject,"hex");i.write(s);const n=Ct(t.certificate.serialNumber,"base64");i.write(n);const a=Ct(t.certificate.certifier,"hex");i.write(a);const o=this.encodeOutpoint(t.certificate.revocationOutpoint??"");i.write(o);const c=Ct(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=Ct(t,"utf8"),s=Ct(e,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(s.length),i.write(s)}i.writeVarIntNum(t.fieldsToReveal.length);for(const e of t.fieldsToReveal){const t=Ct(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}i.write(Ct(t.verifier,"hex")),i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason));const d=await this.transmit("proveCertificate",e,i.toArray()),u=new $t(d),l=u.readVarIntNum(),f={};for(let t=0;t<l;t++){const t=u.readVarIntNum(),e=Lt(u.read(t)),i=u.readVarIntNum();f[e]=Dt(u.read(i))}return{keyringForVerifier:f}}async relinquishCertificate(t,e){const i=new Kt,r=Ct(t.type,"base64");i.write(r);const s=Ct(t.serialNumber,"base64");i.write(s);const n=Ct(t.certifier,"hex");return i.write(n),await this.transmit("relinquishCertificate",e,i.toArray()),{relinquished:!0}}parseDiscoveryResult(t){const e=new $t(t),i=e.readVarIntNum(),r=[];for(let t=0;t<i;t++){const t=e.readVarIntNum(),i=e.read(t),s=ji.fromBinary(i),n=e.readVarIntNum(),a=Lt(e.read(n)),o=e.readVarIntNum(),c=Lt(e.read(o)),h=e.readVarIntNum(),d=Lt(e.read(h)),u=e.readUInt8(),l={},f=e.readVarIntNum();for(let t=0;t<f;t++){const t=e.readVarIntNum(),i=Lt(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=Lt(e.read(t)),r=e.readVarIntNum();p[i]=Lt(e.read(r))}r.push({...s,signature:s.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 Kt;i.write(Ct(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 Kt,r=Object.keys(t.attributes);i.writeVarIntNum(r.length);for(let e=0;e<r.length;e++)i.writeVarIntNum(r[e].length),i.write(Ct(r[e],"utf8")),i.writeVarIntNum(t.attributes[r[e]].length),i.write(Ct(t.attributes[r[e]],"utf8"));"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const s=await this.transmit("discoverByAttributes",e,i.toArray());return this.parseDiscoveryResult(s)}async isAuthenticated(t,e){return{authenticated:1===(await this.transmit("isAuthenticated",e))[0]}}async waitForAuthentication(t,e){return await this.transmit("waitForAuthentication",e),{authenticated:!0}}async getHeight(t,e){const i=await this.transmit("getHeight",e);return{height:new $t(i).readVarIntNum()}}async getHeaderForHeight(t,e){const i=new Kt;i.writeVarIntNum(t.height);const r=await this.transmit("getHeaderForHeight",e,i.toArray());return{header:Tt(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:Lt(i)}}}class Gi{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 $t(t),i=e.readUInt8(),r=zi[i];if(void 0===r||""===r)throw new Error(`Invalid call code: ${i}`);const s=e.readUInt8();let n;if(s>0){const t=e.read(s);n=Lt(t)}const a=e.read(),o=await fetch(`${this.baseUrl}/${r}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:n??""},body:new Uint8Array(a)}),c=await o.arrayBuffer();return Array.from(new Uint8Array(c))}}class Xi extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(t,e,i,r,s){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=t,this.sendWithResults=e,this.txid=i,this.tx=r,this.noSendChange=s,this.code=5,this.name=this.constructor.name}}class Ji{baseUrl;httpClient;originator;api;constructor(t,e="http://localhost:3321",i=fetch){this.baseUrl=e,this.originator=t,this.httpClient=i;const r="undefined"!=typeof window&&"undefined"!=typeof document&&"file://"!==window?.origin;this.api=async(t,e)=>{const s=!r&&this.originator?function(t,e="http"){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(t))try{return new URL(t).origin}catch{}try{return new URL(`${e}://${t}`).origin}catch{throw new Error(`Invalid originator value: ${t}`)}}(this.originator,"http"):void 0;r||void 0!==s||console.error("Originator is required in Node.js environments");const n=await await i(`${this.baseUrl}/${t}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...s?{Origin:s}:{},...s?{Originator:s}:{}},body:JSON.stringify(e)}),a=await n.json();if(!n.ok){if(400===n.status&&a.isError&&5===a.code)throw new Xi(a.reviewActionResults,a.sendWithResults,a.txid,a.tx,a.noSendChange);{const i={call:t,args:e,message:a.message??`HTTP Client error ${n.status}`};throw new Error(JSON.stringify(i))}}return a}}async createAction(t){return await this.api("createAction",t)}async signAction(t){return await this.api("signAction",t)}async abortAction(t){return await this.api("abortAction",t)}async listActions(t){return await this.api("listActions",t)}async internalizeAction(t){return await this.api("internalizeAction",t)}async listOutputs(t){return await this.api("listOutputs",t)}async relinquishOutput(t){return await this.api("relinquishOutput",t)}async getPublicKey(t){return await this.api("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.api("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.api("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.api("encrypt",t)}async decrypt(t){return await this.api("decrypt",t)}async createHmac(t){return await this.api("createHmac",t)}async verifyHmac(t){return await this.api("verifyHmac",t)}async createSignature(t){return await this.api("createSignature",t)}async verifySignature(t){return await this.api("verifySignature",t)}async acquireCertificate(t){return await this.api("acquireCertificate",t)}async listCertificates(t){return await this.api("listCertificates",t)}async proveCertificate(t){return await this.api("proveCertificate",t)}async relinquishCertificate(t){return await this.api("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.api("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.api("discoverByAttributes",t)}async isAuthenticated(t){return await this.api("isAuthenticated",t)}async waitForAuthentication(t){return await this.api("waitForAuthentication",t)}async getHeight(t){return await this.api("getHeight",t)}async getHeaderForHeight(t){return await this.api("getHeaderForHeight",t)}async getNetwork(t){return await this.api("getNetwork",t)}async getVersion(t){return await this.api("getVersion",t)}}class Yi{domain;constructor(t="*"){if("object"!=typeof window)throw new Error("The XDM substrate requires a global window object.");if(!window.hasOwnProperty("ReactNativeWebView"))throw new Error("The window object does not have a ReactNativeWebView property.");if("function"!=typeof window.ReactNativeWebView.postMessage)throw new Error("The window.ReactNativeWebView property does not seem to support postMessage calls.");this.domain=t}async invoke(t,e){return await new Promise(((i,r)=>{const s=Dt(xe(12)),n=t=>{const e=JSON.parse(t.data);if("CWI"===e.type&&e.id===s&&!0!==e.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",n),"error"===e.status){const t=new Hi(e.description,e.code);r(t)}else i(e.result)};window.addEventListener("message",n),window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:s,call:t,args:e}))}))}async createAction(t){return await this.invoke("createAction",t)}async signAction(t){return await this.invoke("signAction",t)}async abortAction(t){return await this.invoke("abortAction",t)}async listActions(t){return await this.invoke("listActions",t)}async internalizeAction(t){return await this.invoke("internalizeAction",t)}async listOutputs(t){return await this.invoke("listOutputs",t)}async relinquishOutput(t){return await this.invoke("relinquishOutput",t)}async getPublicKey(t){return await this.invoke("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.invoke("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.invoke("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.invoke("encrypt",t)}async decrypt(t){return await this.invoke("decrypt",t)}async createHmac(t){return await this.invoke("createHmac",t)}async verifyHmac(t){return await this.invoke("verifyHmac",t)}async createSignature(t){return await this.invoke("createSignature",t)}async verifySignature(t){return await this.invoke("verifySignature",t)}async acquireCertificate(t){return await this.invoke("acquireCertificate",t)}async listCertificates(t){return await this.invoke("listCertificates",t)}async proveCertificate(t){return await this.invoke("proveCertificate",t)}async relinquishCertificate(t){return await this.invoke("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.invoke("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.invoke("discoverByAttributes",t)}async isAuthenticated(t){return await this.invoke("isAuthenticated",t)}async waitForAuthentication(t){return await this.invoke("waitForAuthentication",t)}async getHeight(t){return await this.invoke("getHeight",t)}async getHeaderForHeight(t){return await this.invoke("getHeaderForHeight",t)}async getNetwork(t){return await this.invoke("getNetwork",t)}async getVersion(t){return await this.invoke("getVersion",t)}}class Zi{substrate;originator;constructor(t="auto",e){"Cicada"===t&&(t=new Wi(new Gi(e))),"window.CWI"===t&&(t=new Vi),"XDM"===t&&(t=new $i),"json-api"===t&&(t=new Ji(e)),"react-native"===t&&(t=new Yi(e)),"secure-json-api"===t&&(t=new Ji(e,"https://localhost:2121")),this.substrate=t,this.originator=e}async connectToSubstrate(){if("object"==typeof this.substrate)return;const t=async(t,e)=>{try{const i=t();let r;return r="number"==typeof e?await Promise.race([i.getVersion({}),new Promise(((t,i)=>setTimeout((()=>i(new Error("Timed out."))),e)))]):await i.getVersion({}),"object"!=typeof r||"string"!=typeof r.version?{success:!1}:{success:!0,sub:i}}catch{return{success:!1}}},e=[t((()=>new Vi)),t((()=>new Ji(this.originator,"https://localhost:2121"))),t((()=>new Ji(this.originator))),t((()=>new Yi(this.originator))),t((()=>new Wi(new Gi(this.originator))))],i=(await Promise.allSettled(e)).filter((t=>"fulfilled"===t.status&&t.value.success&&void 0!==t.value.sub)).map((t=>t.value.sub));if(i.length>0)return void(this.substrate=i[0]);const r=await t((()=>new $i),200);if(!r.success||void 0===r.sub)throw new Error("No wallet available over any communication substrate. Install a BSV wallet today!");this.substrate=r.sub}async createAction(t){return 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 Qi extends ji{keyring;decryptedFields;constructor(t,e,i,r,s,n,a,o,c){super(t,e,i,r,s,n,o),this.keyring=a,this.decryptedFields=c}static fromCertificate(t,e){return new Qi(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,e,t.signature)}async decryptFields(t,e,i,r){if(null==this.keyring||0===Object.keys(this.keyring).length)throw new Error("A keyring is required to decrypt certificate fields for the verifier.");try{const s={};for(const n in this.keyring){const{plaintext:a}=await t.decrypt({ciphertext:Ct(this.keyring[n],"base64"),...ji.getCertificateFieldEncryptionDetails(n,this.serialNumber),counterparty:this.subject,privileged:e,privilegedReason:i},r),o=new Qe(a).decrypt(Ct(this.fields[n],"base64"));s[n]=Lt(o)}return s}catch(t){throw new Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(t instanceof Error?t.message:t)}`)}}}class tr{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 er(t,e,i="self",r){const s=Ct(t,"base64"),n=s.slice(0,16),a=s.slice(16),{valid:o}=await e.verifyHmac({data:n,hmac:a,protocolID:[2,"server hmac"],keyID:Lt(n),counterparty:i},r);return o}async function ir(t,e="self",i){const r=xe(16),{hmac:s}=await t.createHmac({protocolID:[2,"server hmac"],keyID:Lt(r),data:r,counterparty:e},i);return Dt([...r,...s])}const rr=async(t,e,i,r)=>{const s=await t.listCertificates({certifiers:e.certifiers,types:Object.keys(e.types)},r);return await Promise.all(s.certificates.map((async s=>{const{keyringForVerifier:n}=await t.proveCertificate({certificate:s,fieldsToReveal:e.types[s.type],verifier:i},r);return new Qi(s.type,s.serialNumber,s.subject,s.certifier,s.revocationOutpoint,s.fields,n,s.signature)})))},sr=async(t,e,i,r)=>{if(null==e.certificates||0===e.certificates.length)throw new Error("No certificates were provided in the AuthMessage.");await Promise.all(e.certificates.map((async s=>{if(s.subject!==e.identityKey)throw new Error(`The subject of one of your certificates ("${s.subject}") is not the same as the request sender ("${e.identityKey}").`);const n=new Qi(s.type,s.serialNumber,s.subject,s.certifier,s.revocationOutpoint,s.fields,s.keyring,s.signature);if(!await n.verify())throw new Error(`The signature for the certificate with serial number ${n.serialNumber} is invalid!`);if(null!=i){const{certifiers:t,types:e}=i;if(!t.includes(n.certifier))throw new Error(`Certificate with serial number ${n.serialNumber} has an unrequested certifier: ${n.certifier}`);if(null==e[n.type])throw new Error(`Certificate with type ${n.type} was not requested`)}await n.decryptFields(t,void 0,void 0,r)})))},nr="0.1";class ar{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;constructor(t,e,i,r,s,n){this.wallet=t,this.originator=n,this.transport=e,this.certificatesToRequest=i??{certifiers:[],types:{}},this.transport.onData(this.handleIncomingMessage.bind(this)).catch((t=>{throw t})),this.sessionManager=null!=r?r:new tr,this.autoPersistLastSession=!1!==s}async toPeer(t,e,i){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof e&&(e=this.lastInteractedWithPeer);const r=await this.getAuthenticatedSession(e,i),s=Dt(xe(32)),{signature:n}=await this.wallet.createSignature({data:t,protocolID:[2,"auth message signature"],keyID:`${s} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey},this.originator),a={version:nr,messageType:"general",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,nonce:s,yourNonce:r.peerNonce,payload:t,signature:n};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),s=Dt(xe(32)),{signature:n}=await this.wallet.createSignature({data:Ct(JSON.stringify(t),"utf8"),protocolID:[2,"auth message signature"],keyID:`${s} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey},this.originator),a={version:nr,messageType:"certificateRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,nonce:s,initialNonce:r.sessionNonce,yourNonce:r.peerNonce,requestedCertificates:t,signature:n};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 ir(this.wallet,void 0,this.originator),r=Date.now();this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:i,peerIdentityKey:t,lastUpdate:r});const s={version:nr,messageType:"initialRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,initialNonce:i,requestedCertificates:this.certificatesToRequest};return await this.transport.send(s),await this.waitForInitialResponse(i,e)}async waitForInitialResponse(t,e=1e4){return await new Promise(((i,r)=>{const s=this.listenForInitialResponse(t,(t=>{clearTimeout(n),this.stopListeningForInitialResponses(s),i(t)})),n=setTimeout((()=>{this.stopListeningForInitialResponses(s),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!==nr)throw new Error(`Invalid or unsupported message auth version! Received: ${t.version}, expected: ${nr}`);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 ir(this.wallet,void 0,this.originator),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 rr(this.wallet,t.requestedCertificates,t.identityKey,this.originator));const{signature:s}=await this.wallet.createSignature({data:Ct(t.initialNonce+e,"base64"),protocolID:[2,"auth message signature"],keyID:`${t.initialNonce} ${e}`,counterparty:t.identityKey},this.originator),n={version:nr,messageType:"initialResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,initialNonce:e,yourNonce:t.initialNonce,certificates:r,requestedCertificates:this.certificatesToRequest,signature:s};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=t.identityKey),await this.transport.send(n)}async processInitialResponse(t){if(!await er(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Initial response nonce verification failed from peer: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Peer session not found for peer: ${t.identityKey}`);const i=Ct((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},this.originator);if(!r)throw new Error(`Unable to verify initial response signature for peer: ${t.identityKey}`);if(e.peerNonce=t.initialNonce,e.peerIdentityKey=t.identityKey,e.isAuthenticated=!0,e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),this.certificatesToRequest?.certifiers?.length>0&&t.certificates?.length>0&&(await sr(this.wallet,t,this.certificatesToRequest,this.originator),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 rr(this.wallet,t.requestedCertificates,t.identityKey,this.originator);await this.sendCertificateResponse(t.identityKey,e)}}async processCertificateRequest(t){if(!await er(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for certificate request message from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{valid:i}=await this.wallet.verifySignature({data:Ct(JSON.stringify(t.requestedCertificates),"utf8"),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:e.peerIdentityKey},this.originator);if(!i)throw new Error(`Invalid signature in certificate request message from ${e.peerIdentityKey}`);if(e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),null!=t.requestedCertificates&&Array.isArray(t.requestedCertificates.certifiers)&&t.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach((e=>{e(t.identityKey,t.requestedCertificates)}));else{const e=await rr(this.wallet,t.requestedCertificates,t.identityKey,this.originator);await this.sendCertificateResponse(t.identityKey,e)}}async sendCertificateResponse(t,e){const i=await this.getAuthenticatedSession(t),r=Dt(xe(32)),{signature:s}=await this.wallet.createSignature({data:Ct(JSON.stringify(e),"utf8"),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),n={version:nr,messageType:"certificateResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,certificates:e,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(n)}catch(t){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 er(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for certificate response from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{valid:i}=await this.wallet.verifySignature({data:Ct(JSON.stringify(t.certificates),"utf8"),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:t.identityKey},this.originator);if(!i)throw new Error(`Unable to verify certificate response signature for peer: ${t.identityKey}`);await sr(this.wallet,t,t.requestedCertificates,this.originator),this.onCertificatesReceivedCallbacks.forEach((e=>{e(t.identityKey,t.certificates??[])})),e.lastUpdate=Date.now(),this.sessionManager.updateSession(e)}async processGeneralMessage(t){if(!await er(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for general message from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{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},this.originator);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 or="undefined"!=typeof window?fetch.bind(window):fetch;class cr{onDataCallback;fetchClient;baseUrl;constructor(t,e=or){this.fetchClient=e,this.baseUrl=t}async send(t){if(null==this.onDataCallback)throw new Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==t.messageType)return await new Promise(((e,i)=>{(async()=>{try{const i=this.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||null==this.onDataCallback)throw new Error("HTTP server failed to authenticate");{const t=await r.json();this.onDataCallback(t)}"initialRequest"===t.messageType&&e()}catch(t){i(t)}})()}));{const e=this.deserializeRequestPayload(t.payload),i=`${this.baseUrl}${e.urlPostfix}`,r=e;if("object"!=typeof e.headers&&(r.headers={}),r.headers["x-bsv-auth-version"]=t.version,r.headers["x-bsv-auth-identity-key"]=t.identityKey,r.headers["x-bsv-auth-nonce"]=t.nonce,r.headers["x-bsv-auth-your-nonce"]=t.yourNonce,r.headers["x-bsv-auth-signature"]=Tt(t.signature),r.headers["x-bsv-auth-request-id"]=e.requestId,null!=r.body){const t=r.headers;if(null==t["content-type"])throw new Error("Content-Type header is required for requests with a body.");const e=String(t["content-type"]??"");e.includes("application/json")||e.includes("application/x-www-form-urlencoded")||e.includes("text/plain")?r.body=Lt(r.body):r.body=new Uint8Array(r.body)}const s=await this.fetchClient(i,{method:r.method,headers:r.headers,body:r.body});if(500===s.status&&null==s.headers.get("x-bsv-auth-request-id")&&null==s.headers.get("x-bsv-auth-requested-certificates")){const t=await s.json();throw new Error(`HTTP ${s.status} - ${JSON.stringify(t)}`)}const n=await s.arrayBuffer(),a=new Kt;null!=s.headers.get("x-bsv-auth-request-id")&&a.write(Ct(s.headers.get("x-bsv-auth-request-id"),"base64")),a.writeVarIntNum(s.status);const o=[];s.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=Ct(o[t][0],"utf8");a.writeVarIntNum(e.length),a.write(e);const i=Ct(o[t][1],"utf8");a.writeVarIntNum(i.length),a.write(i)}if(null!=n){const t=Array.from(new Uint8Array(n));a.writeVarIntNum(t.length),a.write(t)}else a.writeVarIntNum(-1);const c={version:s.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===s.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:s.headers.get("x-bsv-auth-identity-key"),nonce:s.headers.get("x-bsv-auth-nonce"),yourNonce:s.headers.get("x-bsv-auth-your-nonce"),requestedCertificates:JSON.parse(s.headers.get("x-bsv-auth-requested-certificates")),payload:a.toArray(),signature:Ct(s.headers.get("x-bsv-auth-signature"),"hex")};if(null==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 $t(t),i=Dt(e.read(32)),r=e.readVarIntNum();let s="GET";r>0&&(s=Lt(e.read(r)));const n=e.readVarIntNum();let a="";n>0&&(a=Lt(e.read(n)));const o=e.readVarIntNum();let c="";o>0&&(c=Lt(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=Lt(i),s=e.readVarIntNum(),n=e.read(s),a=Lt(n);h[r]=a}let u;const l=e.readVarIntNum();return l>0&&(u=e.read(l)),{urlPostfix:a+c,method:s,headers:h,body:u,requestId:i}}}class hr{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(t,e,i,r){this.wallet=t,this.requestedCertificates=e,this.sessionManager=i??new tr,this.originator=r}async fetch(t,e={}){if("number"==typeof e.retryCounter){if(e.retryCounter<=0)throw new Error("Request failed after maximum number of retries.");e.retryCounter--}const i=await new Promise((async(i,r)=>{try{const{method:s="GET",headers:n={},body:a}=e,o=new URL(t),c=o.origin;let h;if(void 0===this.peers[c]){const t=new cr(c);h={peer:new ar(this.wallet,t,this.requestedCertificates,this.sessionManager,void 0,this.originator),pendingCertificateRequests:[]},this.peers[c]=h,this.peers[c].peer.listenForCertificatesReceived(((t,e)=>{this.certificatesReceived.push(...e)})),this.peers[c].peer.listenForCertificatesRequested((async(t,e)=>{try{this.peers[c].pendingCertificateRequests.push(!0);const i=await rr(this.wallet,e,t,this.originator);await this.peers[c].peer.sendCertificateResponse(t,i)}finally{await new Promise((t=>setTimeout(t,500))),this.peers[c].pendingCertificateRequests.shift()}}))}else{if(!1===this.peers[c].supportsMutualAuth){try{const r=await this.handleFetchAndValidate(t,e,this.peers[c]);i(r)}catch(t){r(t)}return}h=this.peers[c]}const d=xe(32),u=Dt(d),l=await this.serializeRequest(s,n,a,o,d);this.callbacks[u]={resolve:i,reject:r};const f=h.peer.listenForGeneralMessages(((t,e)=>{const i=new $t(e);if(Dt(i.read(32))!==u)return;h.peer.stopListeningForGeneralMessages(f),this.peers[c].identityKey=t,this.peers[c].supportsMutualAuth=!0;const r=i.readVarIntNum(),s={},n=i.readVarIntNum();if(n>0)for(let t=0;t<n;t++){const t=i.readVarIntNum(),e=i.read(t),r=Lt(e),n=i.readVarIntNum(),a=i.read(n),o=Lt(a);s[r]=o}let a;s["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(s)});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 s=>{if(s.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(s.message.includes("HTTP server failed to authenticate"))try{const r=await this.handleFetchAndValidate(t,e,h);return void i(r)}catch(t){r(t)}else r(s)}))}catch(t){r(t)}}));return 402===i.status?await this.handlePaymentAndRetry(t,e,i):i}async sendCertificateRequest(t,e){const i=new URL(t).origin;let r;if(void 0!==this.peers[i])r={peer:this.peers[i].peer};else{const t=new cr(i);r={peer:new ar(this.wallet,t,this.requestedCertificates,this.sessionManager,this.originator)},this.peers[i]=r}return await new Promise((async(t,i)=>{const s=r.peer.listenForCertificatesReceived(((e,i)=>{r.peer.stopListeningForCertificatesReceived(s),this.certificatesReceived.push(...i),t(i)}));try{await r.peer.requestCertificates(e,r.identityKey)}catch(t){r.peer.stopListeningForCertificatesReceived(s),i(t)}}))}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(t,e,i,r,s){const n=new Kt;if(n.write(s),n.writeVarIntNum(t.length),n.write(Ct(t)),r.pathname.length>0){const t=Ct(r.pathname);n.writeVarIntNum(t.length),n.write(t)}else n.writeVarIntNum(-1);if(r.search.length>0){const t=Ct(r.search);n.writeVarIntNum(t.length),n.write(t)}else n.writeVarIntNum(-1);const a=[];for(let[t,i]of Object.entries(e))if(t=t.toLowerCase(),t.startsWith("x-bsv-")||"authorization"===t){if(t.startsWith("x-bsv-auth"))throw new Error("No BSV auth headers allowed here!");a.push([t,i])}else{if(!t.startsWith("content-type"))throw new Error("Unsupported header in the simplified fetch implementation. Only content-type, authorization, and x-bsv-* headers are supported.");i=i.split(";")[0].trim(),a.push([t,i])}a.sort((([t],[e])=>t.localeCompare(e))),n.writeVarIntNum(a.length);for(let t=0;t<a.length;t++){const e=Ct(a[t][0],"utf8");n.writeVarIntNum(e.length),n.write(e);const i=Ct(a[t][1],"utf8");n.writeVarIntNum(i.length),n.write(i)}if(["POST","PUT","PATCH","DELETE"].includes(t.toUpperCase())&&void 0===i){const t=a.find((([t])=>"content-type"===t));i=t&&t[1].includes("application/json")?"{}":""}if(i){const t=await this.normalizeBodyToNumberArray(i);n.writeVarIntNum(t.length),n.write(t)}else n.writeVarIntNum(-1);return n}async handleFetchAndValidate(t,e,i){const r=await fetch(t,e);if(r.headers.forEach((t=>{if(t.toLocaleLowerCase().startsWith("x-bsv"))throw new Error("The server is trying to claim it has been authenticated when it has not!")})),r.ok)return i.supportsMutualAuth=!1,r;throw new Error(`Request failed with status: ${r.status}`)}async handlePaymentAndRetry(t,e={},i){const r=i.headers.get("x-bsv-payment-version");if(!r||"1.0"!==r)throw new Error(`Unsupported x-bsv-payment-version response header. Client version: 1.0, Server version: ${r}`);const s=i.headers.get("x-bsv-payment-satoshis-required");if(!s)throw new Error("Missing x-bsv-payment-satoshis-required response header.");const n=parseInt(s);if(isNaN(n)||n<=0)throw new Error("Invalid x-bsv-payment-satoshis-required response header value.");const a=i.headers.get("x-bsv-auth-identity-key");if("string"!=typeof a)throw new Error("Missing x-bsv-auth-identity-key response header.");const o=i.headers.get("x-bsv-payment-derivation-prefix");if("string"!=typeof o||o.length<1)throw new Error("Missing x-bsv-payment-derivation-prefix response header.");const c=await ir(this.wallet,void 0,this.originator),{publicKey:h}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${o} ${c}`,counterparty:a},this.originator),d=(new bi).lock(_e.fromString(h).toAddress()).toHex(),{tx:u}=await this.wallet.createAction({description:`Payment for request to ${new URL(t).origin}`,outputs:[{satoshis:n,lockingScript:d,customInstructions:JSON.stringify({derivationPrefix:o,derivationSuffix:c,payee:a}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}},this.originator);return e.headers=e.headers||{},e.headers["x-bsv-payment"]=JSON.stringify({derivationPrefix:o,derivationSuffix:c,transaction:Dt(u)}),e.retryCounter??=3,this.fetch(t,e)}async normalizeBodyToNumberArray(t){if(null==t)return[];if("object"==typeof t)return Ct(JSON.stringify(t,"utf8"));if(Array.isArray(t)&&t.every((t=>"number"==typeof t)))return t;if("string"==typeof t)return Ct(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 Ct(i,"utf8")}if(t instanceof URLSearchParams)return Ct(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 dr{pushDrop;static decode(t){const e=yi.decode(t);if(e.fields.length<4)throw new Error("Invalid SHIP/SLAP advertisement!");const i=Lt(e.fields[0]);if("SHIP"!==i&&"SLAP"!==i)throw new Error("Invalid protocol type!");return{protocol:i,identityKey:Tt(e.fields[1]),domain:Lt(e.fields[2]),topicOrService:Lt(e.fields[3])}}constructor(t){this.pushDrop=new yi(t)}async lock(t,e,i){const{publicKey:r}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([Ct(t,"utf8"),Ct(r,"hex"),Ct(e,"utf8"),Ct(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 ur="undefined"!=typeof window?fetch.bind(window):fetch,lr=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],fr=["https://testnet-users.bapp.dev"];class pr{fetchClient;allowHTTP;constructor(t=ur,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="undefined"!=typeof AbortController?new AbortController:void 0,s=setTimeout((()=>{try{r?.abort()}catch{}}),i);try{const i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:e.service,query:e.query}),signal:r?.signal},s=await this.fetchClient(`${t}/lookup`,i);if(!s.ok)throw new Error(`Failed to facilitate lookup (HTTP ${s.status})`);return await s.json()}catch(t){if("AbortError"===t?.name)throw new Error("Request timed out");throw t}finally{clearTimeout(s)}}}class br{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(t={}){this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new pr(void 0,"local"===this.networkPreset),this.slapTrackers=t.slapTrackers??("mainnet"===this.networkPreset?lr:fr),this.hostOverrides=t.hostOverrides??{},this.additionalHosts=t.additionalHosts??{},this.hostsTtlMs=t.cache?.hostsTtlMs??3e5,this.hostsMaxEntries=t.cache?.hostsMaxEntries??128,this.txMemoTtlMs=t.cache?.txMemoTtlMs??6e5,this.hostsCache=new Map,this.hostsInFlight=new Map,this.txMemo=new Map}async query(t,e){let i=[];if(i="ls_slap"===t.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[t.service]?this.hostOverrides[t.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.getCompetentHostsCached(t.service),this.additionalHosts[t.service]?.length>0){const e=this.additionalHosts[t.service],r=new Set(i);for(const t of e)r.has(t)||i.push(t)}if(i.length<1)throw new Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${t.service}`);const r=await Promise.allSettled(i.map((async i=>await this.facilitator.lookup(i,t,e)))),s=new Map;for(const t of r){if("fulfilled"!==t.status)continue;const e=t.value;if("output-list"===e?.type&&Array.isArray(e.outputs))for(const t of e.outputs){const e="object"!=typeof(n=t.beef)?"":n.join(",");let i=this.txMemo.get(e);const r=Date.now();if("object"!=typeof i||null===i||i.expiresAt<=r)try{i={txId:Li.fromBEEF(t.beef).id("hex"),expiresAt:r+this.txMemoTtlMs},this.txMemo.size>4096&&this.evictOldest(this.txMemo),this.txMemo.set(e,i)}catch{continue}const a=`${i.txId}.${t.outputIndex}`;s.set(a,t)}}var n;return{type:"output-list",outputs:Array.from(s.values())}}async getCompetentHostsCached(t){const e=Date.now(),i=this.hostsCache.get(t);if("object"==typeof i&&i.expiresAt>e)return i.hosts.slice();if("object"==typeof i&&i.expiresAt<=e)return this.hostsInFlight.has(t)||this.hostsInFlight.set(t,this.refreshHosts(t).finally((()=>{this.hostsInFlight.delete(t)}))),i.hosts.slice();if(this.hostsInFlight.has(t))try{const e=await this.hostsInFlight.get(t);if("object"!=typeof e)throw new Error("Hosts is not defined.");return e.slice()}catch{}const r=this.refreshHosts(t).finally((()=>{this.hostsInFlight.delete(t)}));return this.hostsInFlight.set(t,r),(await r).slice()}async refreshHosts(t){const e=await this.findCompetentHosts(t),i=Date.now()+this.hostsTtlMs;if(!this.hostsCache.has(t)&&this.hostsCache.size>=this.hostsMaxEntries){const t=this.hostsCache.keys().next().value;void 0!==t&&this.hostsCache.delete(t)}return this.hostsCache.set(t,{hosts:e,expiresAt:i}),e}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)continue;const i=e.value;if("output-list"===i.type)for(const e of i.outputs)try{const i=Li.fromBEEF(e.beef),s=i.outputs[e.outputIndex]?.lockingScript;if("object"!=typeof s||null===s)continue;const n=dr.decode(s);if(n.topicOrService!==t||"SLAP"!==n.protocol)continue;"string"==typeof n.domain&&n.domain.length>0&&r.add(n.domain)}catch{continue}}return[...r]}evictOldest(t){const e=t.keys().next().value;void 0!==e&&t.delete(e)}}class gr{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 Kt;t.writeVarIntNum(e.beef.length),t.write(e.beef),t.write(e.offChainValues),r=new Uint8Array(t.toArray())}else r=new Uint8Array(e.beef);const s=await fetch(`${t}/submit`,{method:"POST",headers:i,body:r});if(s.ok)return await s.json();throw new Error("Failed to facilitate broadcast")}}class yr{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 gr(void 0,"local"===this.networkPreset),this.resolver=e.resolver??new br({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 s=Object.entries(r).map((async([t,r])=>{try{const s=await this.facilitator.send(t,{beef:e,offChainValues:i,topics:[...r]});if(null==s||0===Object.keys(s).length)throw new Error("Steak has no topics.");return{host:t,success:!0,steak:s}}catch(e){return console.error(e),{host:t,success:!1,error:e}}})),n=(await Promise.all(s)).filter((t=>t.success));if(0===n.length)return{status:"error",code:"ERR_ALL_HOSTS_REJECTED",description:`All ${this.networkPreset} topical hosts have rejected the transaction.`};const a={};for(const t of n){const e=t.host,i=t.steak,r=new Set;for(const[t,e]of Object.entries(i)){const i=e.outputsToAdmit,s=e.coinsToRetain,n=e.coinsRemoved;(i?.length>0||s?.length>0||n?.length>0)&&r.add(t)}a[e]=r}let o,c,h,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 ${n.length} Overlay Services ${1===n.length?"host":"hosts"}.`})}checkAcknowledgmentFromAllHosts(t,e,i){for(const r of Object.values(t))if("all"===i){for(const t of e)if(!r.has(t))return!1}else if("any"===i){let t=!1;for(const i of e)if(r.has(i)){t=!0;break}if(!t)return!1}return!0}checkAcknowledgmentFromAnyHost(t,e,i){if("all"===i){for(const i of Object.values(t)){let t=!0;for(const r of e)if(!i.has(r)){t=!1;break}if(t)return!0}return!1}for(const i of Object.values(t))for(const t of e)if(i.has(t))return!0;return!1}checkAcknowledgmentFromSpecificHosts(t,e){for(const[i,r]of Object.entries(e)){const e=t[i];if(null==e)return!1;let s,n;if("all"===r||"any"===r)n=r,s=this.topics;else{if(!Array.isArray(r))continue;s=r,n="all"}if("all"===n){for(const t of s)if(!e.has(t))return!1}else if("any"===n){let t=!1;for(const i of s)if(e.has(i)){t=!0;break}if(!t)return!1}}return!0}async findInterestedHosts(){if("local"===this.networkPreset){const t=new Set;for(let e=0;e<this.topics.length;e++)t.add(this.topics[e]);return{"http://localhost:8080":t}}const t={},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=Li.fromBEEF(i.beef).outputs[i.outputIndex].lockingScript,r=dr.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 mr=Object.create(null);mr.open="0",mr.close="1",mr.ping="2",mr.pong="3",mr.message="4",mr.upgrade="5",mr.noop="6";const wr=Object.create(null);Object.keys(mr).forEach((t=>{wr[mr[t]]=t}));const Ir={type:"error",data:"parser error"},vr="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),kr="function"==typeof ArrayBuffer,Sr=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,Er=({type:t,data:e},i,r)=>vr&&e instanceof Blob?i?r(e):_r(e,r):kr&&(e instanceof ArrayBuffer||Sr(e))?i?r(e):_r(new Blob([e]),r):r(mr[t]+(e||"")),_r=(t,e)=>{const i=new FileReader;return i.onload=function(){const t=i.result.split(",")[1];e("b"+(t||""))},i.readAsDataURL(t)};function Pr(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let Or;const xr="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)xr["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const Nr="function"==typeof ArrayBuffer,Ar=(t,e)=>{if("string"!=typeof t)return{type:"message",data:Cr(t,e)};const i=t.charAt(0);return"b"===i?{type:"message",data:Tr(t.substring(1),e)}:wr[i]?t.length>1?{type:wr[i],data:t.substring(1)}:{type:wr[i]}:Ir},Tr=(t,e)=>{if(Nr){const i=(t=>{let e,i,r,s,n,a=.75*t.length,o=t.length,c=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);const h=new ArrayBuffer(a),d=new Uint8Array(h);for(e=0;e<o;e+=4)i=xr[t.charCodeAt(e)],r=xr[t.charCodeAt(e+1)],s=xr[t.charCodeAt(e+2)],n=xr[t.charCodeAt(e+3)],d[c++]=i<<2|r>>4,d[c++]=(15&r)<<4|s>>2,d[c++]=(3&s)<<6|63&n;return h})(t);return Cr(i,e)}return{base64:!0,data:t}},Cr=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,Rr=String.fromCharCode(30);let Br;function Lr(t){return t.reduce(((t,e)=>t+e.length),0)}function Mr(t,e){if(t[0].length===e)return t.shift();const i=new Uint8Array(e);let r=0;for(let s=0;s<e;s++)i[s]=t[0][r++],r===t[0].length&&(t.shift(),r=0);return t.length&&r<t[0].length&&(t[0]=t[0].slice(r)),i}function Dr(t){if(t)return function(t){for(var e in Dr.prototype)t[e]=Dr.prototype[e];return t}(t)}Dr.prototype.on=Dr.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Dr.prototype.once=function(t,e){function i(){this.off(t,i),e.apply(this,arguments)}return i.fn=e,this.on(t,i),this},Dr.prototype.off=Dr.prototype.removeListener=Dr.prototype.removeAllListeners=Dr.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var i,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var s=0;s<r.length;s++)if((i=r[s])===e||i.fn===e){r.splice(s,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},Dr.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),i=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(i){r=0;for(var s=(i=i.slice(0)).length;r<s;++r)i[r].apply(this,e)}return this},Dr.prototype.emitReserved=Dr.prototype.emit,Dr.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Dr.prototype.hasListeners=function(t){return!!this.listeners(t).length};const Fr="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),Vr="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Hr(t,...e){return e.reduce(((e,i)=>(t.hasOwnProperty(i)&&(e[i]=t[i]),e)),{})}const qr=Vr.setTimeout,Ur=Vr.clearTimeout;function Kr(t,e){e.useNativeTimers?(t.setTimeoutFn=qr.bind(Vr),t.clearTimeoutFn=Ur.bind(Vr)):(t.setTimeoutFn=Vr.setTimeout.bind(Vr),t.clearTimeoutFn=Vr.clearTimeout.bind(Vr))}function $r(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class jr extends Error{constructor(t,e,i){super(t),this.description=e,this.context=i,this.type="TransportError"}}class zr extends Dr{constructor(t){super(),this.writable=!1,Kr(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 jr(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=Ar(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 Wr extends zr{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(Rr),r=[];for(let t=0;t<i.length;t++){const s=Ar(i[t],e);if(r.push(s),"error"===s.type)break}return r})(t,this.socket.binaryType).forEach((t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)})),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const i=t.length,r=new Array(i);let s=0;t.forEach(((t,n)=>{Er(t,!1,(t=>{r[n]=t,++s===i&&e(r.join(Rr))}))}))})(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]=$r()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let Gr=!1;try{Gr="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const Xr=Gr;function Jr(){}class Yr extends Wr{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 Zr extends Dr{constructor(t,e,i){super(),this.createRequest=t,Kr(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=Hr(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=Zr.requestsCount++,Zr.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=Jr,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Zr.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 Qr(){for(let t in Zr.requests)Zr.requests.hasOwnProperty(t)&&Zr.requests[t].abort()}Zr.requestsCount=0,Zr.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Qr):"function"==typeof addEventListener&&addEventListener("onpagehide"in Vr?"pagehide":"unload",Qr,!1));const ts=function(){const t=es({xdomain:!1});return t&&null!==t.responseType}();function es(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||Xr))return new XMLHttpRequest}catch(t){}if(!e)try{return new(Vr[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const is="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class rs extends zr{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,i=is?{}:Hr(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;Er(i,this.supportsBinary,(t=>{try{this.doWrite(i,t)}catch(t){}r&&Fr((()=>{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]=$r()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const ss=Vr.WebSocket||Vr.MozWebSocket,ns={websocket:class extends rs{createSocket(t,e,i){return is?new ss(t,e,i):e?new ss(t,e):new ss(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends zr{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){Br||(Br=new TextDecoder);const i=[];let r=0,s=-1,n=!1;return new TransformStream({transform(a,o){for(i.push(a);;){if(0===r){if(Lr(i)<1)break;const t=Mr(i,1);n=!(128&~t[0]),s=127&t[0],r=s<126?3:126===s?1:2}else if(1===r){if(Lr(i)<2)break;const t=Mr(i,2);s=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),r=3}else if(2===r){if(Lr(i)<8)break;const t=Mr(i,8),e=new DataView(t.buffer,t.byteOffset,t.length),n=e.getUint32(0);if(n>Math.pow(2,21)-1){o.enqueue(Ir);break}s=n*Math.pow(2,32)+e.getUint32(4),r=3}else{if(Lr(i)<s)break;const t=Mr(i,s);o.enqueue(Ar(n?t:Br.decode(t),e)),r=0}if(0===s||s>t){o.enqueue(Ir);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=t.readable.pipeThrough(e).getReader(),r=new TransformStream({transform(t,e){!function(t,e){vr&&t.data instanceof Blob?t.data.arrayBuffer().then(Pr).then(e):kr&&(t.data instanceof ArrayBuffer||Sr(t.data))?e(Pr(t.data)):Er(t,!1,(t=>{Or||(Or=new TextEncoder),e(Or.encode(t))}))}(t,(i=>{const r=i.length;let s;if(r<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,r);else if(r<65536){s=new Uint8Array(3);const t=new DataView(s.buffer);t.setUint8(0,126),t.setUint16(1,r)}else{s=new Uint8Array(9);const t=new DataView(s.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(r))}t.data&&"string"!=typeof t.data&&(s[0]|=128),e.enqueue(s),e.enqueue(i)}))}});r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const s=()=>{i.read().then((({done:t,value:e})=>{t||(this.onPacket(e),s())})).catch((t=>{}))};s();const n={type:"open"};this.query.sid&&(n.data=`{"sid":"${this.query.sid}"}`),this._writer.write(n).then((()=>this.onOpen()))}))}))}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const i=t[e],r=e===t.length-1;this._writer.write(i).then((()=>{r&&Fr((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends Yr{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=ts&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Zr(es,this.uri(),t)}}},as=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,os=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function cs(t){if(t.length>8e3)throw"URI too long";const e=t,i=t.indexOf("["),r=t.indexOf("]");-1!=i&&-1!=r&&(t=t.substring(0,i)+t.substring(i,r).replace(/:/g,";")+t.substring(r,t.length));let s=as.exec(t||""),n={},a=14;for(;a--;)n[os[a]]=s[a]||"";return-1!=i&&-1!=r&&(n.source=e,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=function(t,e){const i=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||i.splice(0,1),"/"==e.slice(-1)&&i.splice(i.length-1,1),i}(0,n.path),n.queryKey=function(t,e){const i={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,r){e&&(i[e]=r)})),i}(0,n.query),n}const hs="function"==typeof addEventListener&&"function"==typeof removeEventListener,ds=[];hs&&addEventListener("offline",(()=>{ds.forEach((t=>t()))}),!1);class us extends Dr{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=cs(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=cs(e.host).host);Kr(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)),hs&&(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"})},ds.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&&us.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",us.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,s=t.length;r<s;r++)e=t.charCodeAt(r),e<128?i+=1:e<2048?i+=2:e<55296||e>=57344?i+=3:(r++,i+=4);return i}(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,Fr((()=>{this._onClose("ping timeout")}),this.setTimeoutFn)),t}write(t,e,i){return this._sendPacket("message",t,e,i),this}send(t,e,i){return this._sendPacket("message",t,e,i),this}_sendPacket(t,e,i,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof i&&(r=i,i=null),"closing"===this.readyState||"closed"===this.readyState)return;(i=i||{}).compress=!1!==i.compress;const s={type:t,data:e,options:i};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},i=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?i():t()})):this.upgrading?i():t()),this}_onError(t){if(us.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(),hs&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=ds.indexOf(this._offlineEventListener);-1!==t&&ds.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}us.protocol=4;class ls extends us{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;us.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;us.priorWebsocketSuccess="websocket"===e.name,this.transport.pause((()=>{i||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())}))}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}})))};function s(){i||(i=!0,h(),e.close(),e=null)}const n=t=>{const i=new Error("probe error: "+t);i.transport=e.name,s(),this.emitReserved("upgradeError",i)};function a(){n("transport closed")}function o(){n("socket closed")}function c(t){e&&t.name!==e.name&&s()}const h=()=>{e.removeListener("open",r),e.removeListener("error",n),e.removeListener("close",a),this.off("close",o),this.off("upgrading",c)};e.once("open",r),e.once("error",n),e.once("close",a),this.once("close",o),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn((()=>{i||e.open()}),200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let i=0;i<t.length;i++)~this.transports.indexOf(t[i])&&e.push(t[i]);return e}}class fs extends ls{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=>ns[t])).filter((t=>!!t))),super(t,i)}}const ps="function"==typeof ArrayBuffer,bs=Object.prototype.toString,gs="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===bs.call(Blob),ys="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===bs.call(File);function ms(t){return ps&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||gs&&t instanceof Blob||ys&&t instanceof File}function ws(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,i=t.length;e<i;e++)if(ws(t[e]))return!0;return!1}if(ms(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return ws(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&ws(t[e]))return!0;return!1}function Is(t){const e=[],i=t.data,r=t;return r.data=vs(i,e),r.attachments=e.length,{packet:r,buffers:e}}function vs(t,e){if(!t)return t;if(ms(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]=vs(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]=vs(t[r],e));return i}return t}function ks(t,e){return t.data=Ss(t.data,e),delete t.attachments,t}function Ss(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]=Ss(t[i],e);else if("object"==typeof t)for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=Ss(t[i],e));return t}const Es=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],_s=5;var Ps;!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"}(Ps||(Ps={}));class Os{constructor(t){this.replacer=t}encode(t){return t.type!==Ps.EVENT&&t.type!==Ps.ACK||!ws(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===Ps.EVENT?Ps.BINARY_EVENT:Ps.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==Ps.BINARY_EVENT&&t.type!==Ps.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=Is(t),i=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(i),r}}function xs(t){return"[object Object]"===Object.prototype.toString.call(t)}class Ns extends Dr{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===Ps.BINARY_EVENT;i||e.type===Ps.BINARY_ACK?(e.type=i?Ps.EVENT:Ps.ACK,this.reconstructor=new As(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!ms(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===Ps[i.type])throw new Error("unknown packet type "+i.type);if(i.type===Ps.BINARY_EVENT||i.type===Ps.BINARY_ACK){const r=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const s=t.substring(r,e);if(s!=Number(s)||"-"!==t.charAt(e))throw new Error("Illegal attachments");i.attachments=Number(s)}if("/"===t.charAt(e+1)){const r=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);i.nsp=t.substring(r,e)}else i.nsp="/";const r=t.charAt(e+1);if(""!==r&&Number(r)==r){const r=e+1;for(;++e;){const i=t.charAt(e);if(null==i||Number(i)!=i){--e;break}if(e===t.length)break}i.id=Number(t.substring(r,e+1))}if(t.charAt(++e)){const r=this.tryParse(t.substr(e));if(!Ns.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 Ps.CONNECT:return xs(e);case Ps.DISCONNECT:return void 0===e;case Ps.CONNECT_ERROR:return"string"==typeof e||xs(e);case Ps.EVENT:case Ps.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===Es.indexOf(e[0]));case Ps.ACK:case Ps.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class As{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=ks(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function Ts(t,e,i){return t.on(e,i),function(){t.off(e,i)}}const Cs=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Rs extends Dr{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=[Ts(t,"open",this.onopen.bind(this)),Ts(t,"packet",this.onpacket.bind(this)),Ts(t,"error",this.onerror.bind(this)),Ts(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var i,r,s;if(Cs.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const n={type:Ps.EVENT,data:e,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,i=e.pop();this._registerAckCallback(t,i),n.id=t}const a=null===(r=null===(i=this.io.engine)||void 0===i?void 0:i.transport)||void 0===r?void 0:r.writable,o=this.connected&&!(null===(s=this.io.engine)||void 0===s?void 0:s._hasPingExpired());return this.flags.volatile&&!a||(o?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(t,e){var i;const r=null!==(i=this.flags.timeout)&&void 0!==i?i:this._opts.ackTimeout;if(void 0===r)return void(this.acks[t]=e);const s=this.io.setTimeoutFn((()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))}),r),n=(...t)=>{this.io.clearTimeoutFn(s),e.apply(this,t)};n.withError=!0,this.acks[t]=n}emitWithAck(t,...e){return new Promise(((i,r)=>{const s=(t,e)=>t?r(t):i(e);s.withError=!0,e.push(s),this.emit(t,...e)}))}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const i={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push(((t,...r)=>{if(i===this._queue[0])return null!==t?i.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...r)),i.pending=!1,this._drainQueue()})),this._queue.push(i),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth((t=>{this._sendConnectPacket(t)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:Ps.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 Ps.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 Ps.EVENT:case Ps.BINARY_EVENT:this.onevent(t);break;case Ps.ACK:case Ps.BINARY_ACK:this.onack(t);break;case Ps.DISCONNECT:this.ondisconnect();break;case Ps.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:Ps.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:Ps.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 Bs(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}Bs.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)},Bs.prototype.reset=function(){this.attempts=0},Bs.prototype.setMin=function(t){this.ms=t},Bs.prototype.setMax=function(t){this.max=t},Bs.prototype.setJitter=function(t){this.jitter=t};class Ls extends Dr{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,Kr(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 Bs({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const s=e.parser||i;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new fs(this.uri,this.opts);const e=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const r=Ts(e,"open",(function(){i.onopen(),t&&t()})),s=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},n=Ts(e,"error",s);if(!1!==this._timeout){const t=this._timeout,i=this.setTimeoutFn((()=>{r(),s(new Error("timeout")),e.close()}),t);this.opts.autoUnref&&i.unref(),this.subs.push((()=>{this.clearTimeoutFn(i)}))}return this.subs.push(r),this.subs.push(n),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Ts(t,"ping",this.onping.bind(this)),Ts(t,"data",this.ondata.bind(this)),Ts(t,"error",this.onerror.bind(this)),Ts(t,"close",this.onclose.bind(this)),Ts(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){Fr((()=>{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 Rs(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 Ms={};function Ds(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=cs(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const s=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+s+":"+r.port+e,r.href=r.protocol+"://"+s+(i&&i.port===r.port?"":":"+r.port),r}(t,(e=e||{}).path||"/socket.io"),r=i.source,s=i.id,n=i.path,a=Ms[s]&&n in Ms[s].nsps;let o;return e.forceNew||e["force new connection"]||!1===e.multiplex||a?o=new Ls(r,e):(Ms[s]||(Ms[s]=new Ls(r,e)),o=Ms[s]),i.query&&!e.query&&(e.query=i.queryKey),o.socket(i.path,e)}Object.assign(Ds,{Manager:Ls,Socket:Rs,io:Ds,connect:Ds});class Fs{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 Vs{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 Ct(JSON.stringify(i),"utf8")}decodeEventPayload(t){try{const e=Lt(t);return JSON.parse(e)}catch{return{eventName:"_unknown",data:void 0}}}}let Hs=!1;function qs(...t){Hs&&console.log(...t)}function Us(...t){Hs&&console.warn(...t)}function Ks(...t){console.error(...t)}class $s{host;authFetch;walletClient;socket;myIdentityKey;joinedRooms=new Set;lookupResolver;networkPreset;initialized=!1;originator;constructor(t={}){const{host:e,walletClient:i,enableLogging:r=!1,networkPreset:s="mainnet",originator:n}=t,a="testnet"===this.networkPreset?"https://staging-messagebox.babbage.systems":"https://messagebox.babbage.systems";this.host=e?.trim()??a,this.originator=n,this.walletClient=i??new Zi("auto",n),this.authFetch=new hr(this.walletClient,void 0,void 0,n),this.networkPreset=s,this.lookupResolver=new br({networkPreset:s}),r&&(Hs=!0)}async init(t=this.host){const e=t?.trim();if(""===e)throw new Error("Cannot anoint host: No valid host provided");if(e!==this.host&&(this.initialized=!1,this.host=e),this.initialized)return;const i=await this.getIdentityKey(),[r]=await this.queryAdvertisements(i,e);if(null==r||""===r?.host?.trim()||r?.host!==e){qs("[MB CLIENT] Anointing host:",e);try{const{txid:t}=await this.anointHost(e);if(null==t||""===t.trim())throw new Error("Failed to anoint host: No transaction ID returned")}catch(t){qs("[MB CLIENT] Failed to anoint host, continuing with default functionality:",t)}}this.initialized=!0}async assertInitialized(){this.initialized&&null!=this.host&&""!==this.host.trim()||await this.init()}getJoinedRooms(){return this.joinedRooms}async getIdentityKey(){if(null!=this.myIdentityKey&&""!==this.myIdentityKey.trim())return this.myIdentityKey;qs("[MB CLIENT] Fetching identity key...");try{const t=await this.walletClient.getPublicKey({identityKey:!0},this.originator);return this.myIdentityKey=t.publicKey,qs(`[MB CLIENT] Identity key fetched: ${this.myIdentityKey}`),this.myIdentityKey}catch(t){throw Ks("[MB CLIENT ERROR] Failed to fetch identity key:",t),new Error("Identity key retrieval failed")}}get testSocket(){return this.socket}async initializeConnection(t){if(qs("[MB CLIENT] initializeConnection() STARTED"),null!=this.myIdentityKey&&""!==this.myIdentityKey.trim()||await this.getIdentityKey(),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw Ks("[MB CLIENT ERROR] Identity key is still missing after retrieval!"),new Error("Identity key is missing");if(qs("[MB CLIENT] Setting up WebSocket connection..."),null==this.socket){const e=t??this.host;if("string"!=typeof e||""===e.trim())throw new Error("Cannot initialize WebSocket: No valid host provided");this.socket=function(t,e){const i=Ds(t,e.managerOptions),r=new Fs(i),s=new ar(e.wallet,r,e.requestedCertificates,e.sessionManager,void 0,e.originator);return new Vs(i,s)}(e,{wallet:this.walletClient,originator:this.originator});let i=!1,r=!1;this.socket.on("connect",(()=>{qs("[MB CLIENT] Connected to WebSocket."),i||(qs("[MB CLIENT] Sending authentication data:",this.myIdentityKey),null==this.myIdentityKey||""===this.myIdentityKey.trim()?Ks("[MB CLIENT ERROR] Cannot send authentication: Identity key is missing!"):(this.socket?.emit("authenticated",{identityKey:this.myIdentityKey}),i=!0))})),this.socket.on("authenticationSuccess",(t=>{qs(`[MB CLIENT] WebSocket authentication successful: ${JSON.stringify(t)}`),r=!0})),this.socket.on("authenticationFailed",(t=>{Ks(`[MB CLIENT ERROR] WebSocket authentication failed: ${JSON.stringify(t)}`),r=!1})),this.socket.on("disconnect",(()=>{qs("[MB CLIENT] Disconnected from MessageBox server"),this.socket=void 0,i=!1,r=!1})),this.socket.on("error",(t=>{Ks("[MB CLIENT ERROR] WebSocket error:",t)})),await new Promise(((t,e)=>{setTimeout((()=>{r?(qs("[MB CLIENT] WebSocket fully authenticated and ready!"),t()):e(new Error("[MB CLIENT ERROR] WebSocket authentication timed out!"))}),5e3)}))}}async resolveHostForRecipient(t){const e=await this.queryAdvertisements(t,void 0);return 0===e.length?(Us(`[MB CLIENT] No advertisements for ${t}, using default host ${this.host}`),this.host):e[0].host}async queryAdvertisements(t,e){const i=[];try{const r={identityKey:t??await this.getIdentityKey()};null!=e&&""!==e.trim()&&(r.host=e);const s=await this.lookupResolver.query({service:"ls_messagebox",query:r});if("output-list"!==s.type)throw new Error(`Unexpected result type: ${String(s.type)}`);for(const t of s.outputs)try{const e=Li.fromBEEF(t.beef),r=e.outputs[t.outputIndex].lockingScript,s=yi.decode(r),[,n]=s.fields;if(null==n||0===n.length)throw new Error("Empty host field");i.push({host:Lt(n),txid:e.id("hex"),outputIndex:t.outputIndex,lockingScript:r,beef:t.beef})}catch{}}catch(t){Ks("[MB CLIENT ERROR] _queryAdvertisements failed:",t)}return i}async joinRoom(t,e){if(qs(`[MB CLIENT] Attempting to join WebSocket room: ${t}`),null==this.socket&&(qs("[MB CLIENT] No WebSocket connection. Initializing..."),await this.initializeConnection(e)),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw new Error("[MB CLIENT ERROR] Identity key is not defined");const i=`${this.myIdentityKey??""}-${t}`;if(this.joinedRooms.has(i))qs(`[MB CLIENT] Already joined WebSocket room: ${i}`);else try{qs(`[MB CLIENT] Joining WebSocket room: ${i}`),await(this.socket?.emit("joinRoom",i)),this.joinedRooms.add(i),qs(`[MB CLIENT] Successfully joined room: ${i}`)}catch(t){Ks(`[MB CLIENT ERROR] Failed to join WebSocket room: ${i}`,t)}}async listenForLiveMessages({onMessage:t,messageBox:e,overrideHost:i}){if(qs(`[MB CLIENT] Setting up listener for WebSocket room: ${e}`),null==this.socket&&(qs("[MB CLIENT] No WebSocket connection. Initializing..."),await this.initializeConnection(i)),await this.joinRoom(e,this.originator),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw new Error("[MB CLIENT ERROR] Identity key is missing. Cannot construct room ID.");const r=`${this.myIdentityKey}-${e}`;qs(`[MB CLIENT] Listening for messages in room: ${r}`),this.socket?.on(`sendMessage-${r}`,(e=>{(async()=>{qs(`[MB CLIENT] Received message in room ${r}:`,e);try{let t=e.body;if("string"==typeof t)try{t=JSON.parse(t)}catch{}if(null!=t&&"object"==typeof t&&"string"==typeof t.encryptedMessage){qs(`[MB CLIENT] Decrypting message from ${String(e.sender)}...`);const i=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:e.sender,ciphertext:Ct(t.encryptedMessage,"base64")},this.originator);e.body=Lt(i.plaintext)}else qs("[MB CLIENT] Message is not encrypted."),e.body="string"==typeof t?t:(()=>{try{return JSON.stringify(t)}catch{return"[Error: Unstringifiable message]"}})()}catch(t){Ks("[MB CLIENT ERROR] Failed to parse or decrypt live message:",t),e.body="[Error: Failed to decrypt or parse message]"}t(e)})()}))}async sendLiveMessage({recipient:t,messageBox:e,body:i,messageId:r,skipEncryption:s,checkPermissions:n},a){if(null==t||""===t.trim())throw new Error("[MB CLIENT ERROR] Recipient identity key is required");if(null==e||""===e.trim())throw new Error("[MB CLIENT ERROR] MessageBox is required");if(null==i||"string"==typeof i&&""===i.trim())throw new Error("[MB CLIENT ERROR] Message body cannot be empty");if(await this.joinRoom(e,this.originator),null==this.socket||!this.socket.connected){Us("[MB CLIENT WARNING] WebSocket not connected, falling back to HTTP");const r=a??await this.resolveHostForRecipient(t);return await this.sendMessage({recipient:t,messageBox:e,body:i},r)}let o;try{const e=await this.walletClient.createHmac({data:Array.from((new TextEncoder).encode(JSON.stringify(i))),protocolID:[1,"messagebox"],keyID:"1",counterparty:t},this.originator);o=r??Array.from(e.hmac).map((t=>t.toString(16).padStart(2,"0"))).join("")}catch(t){throw Ks("[MB CLIENT ERROR] Failed to generate HMAC:",t),new Error("Failed to generate message identifier.")}const c=`${t}-${e}`;let h;if(qs(`[MB CLIENT] Sending WebSocket message to room: ${c}`),!0===s)h="string"==typeof i?i:JSON.stringify(i);else{const e=await this.walletClient.encrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t,plaintext:Ct("string"==typeof i?i:JSON.stringify(i),"utf8")},this.originator);h=JSON.stringify({encryptedMessage:Dt(e.ciphertext)})}return await new Promise(((r,a)=>{const d=`sendMessageAck-${c}`;let u=!1;const l=c=>{if(u)return;u=!0;const h=this.socket;if("function"==typeof h?.off&&h.off(d,l),qs("[MB CLIENT] Received WebSocket acknowledgment:",c),null==c||"success"!==c.status){Us("[MB CLIENT] WebSocket message failed or returned unexpected response. Falling back to HTTP.");const c={recipient:t,messageBox:e,body:i,messageId:o,skipEncryption:s,checkPermissions:n};this.resolveHostForRecipient(t).then((async t=>await this.sendMessage(c,t))).then(r).catch(a)}else qs("[MB CLIENT] Message sent successfully via WebSocket:",c),r(c)};this.socket?.on(d,l),this.socket?.emit("sendMessage",{roomId:c,message:{messageId:o,recipient:t,body:h}}),setTimeout((()=>{if(!u){u=!0;const c=this.socket;"function"==typeof c?.off&&c.off(d,l),Us("[CLIENT] WebSocket acknowledgment timed out, falling back to HTTP");const h={recipient:t,messageBox:e,body:i,messageId:o,skipEncryption:s,checkPermissions:n};this.resolveHostForRecipient(t).then((async t=>await this.sendMessage(h,t))).then(r).catch(a)}}),1e4)}))}async leaveRoom(t){if(await this.assertInitialized(),null==this.socket)return void Us("[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}`;qs(`[MB CLIENT] Leaving WebSocket room: ${e}`),this.socket.emit("leaveRoom",e),this.joinedRooms.delete(e)}async disconnectWebSocket(){await this.assertInitialized(),null!=this.socket?(qs("[MB CLIENT] Closing WebSocket connection..."),this.socket.disconnect(),this.socket=void 0):qs("[MB CLIENT] No active WebSocket connection to close.")}async sendMessage(t,e){if(await this.assertInitialized(),null==t.recipient||""===t.recipient.trim())throw new Error("You must provide a message recipient!");if(null==t.messageBox||""===t.messageBox.trim())throw new Error("You must provide a messageBox to send this message into!");if(null==t.body||"string"==typeof t.body&&0===t.body.trim().length)throw new Error("Every message must have a body!");let i,r,s;if(!0===t.checkPermissions)try{qs("[MB CLIENT] Checking permissions and fees for message...");const r=await this.getMessageBoxQuote({recipient:t.recipient,messageBox:t.messageBox},e);if(-1===r.recipientFee)throw new Error("You have been blocked from sending messages to this recipient.");if(r.recipientFee>0||r.deliveryFee>0){const s=r.recipientFee+r.deliveryFee;s>0&&(qs(`[MB CLIENT] Creating payment of ${s} sats for message...`),i=await this.createMessagePayment(t.recipient,r,e),qs("[MB CLIENT] Payment data prepared:",i))}}catch(t){throw new Error(`Permission check failed: ${t instanceof Error?t.message:"Unknown error"}`)}try{const e=await this.walletClient.createHmac({data:Array.from((new TextEncoder).encode(JSON.stringify(t.body))),protocolID:[1,"messagebox"],keyID:"1",counterparty:t.recipient},this.originator);r=t.messageId??Array.from(e.hmac).map((t=>t.toString(16).padStart(2,"0"))).join("")}catch(t){throw Ks("[MB CLIENT ERROR] Failed to generate HMAC:",t),new Error("Failed to generate message identifier.")}if(!0===t.skipEncryption)s="string"==typeof t.body?t.body:JSON.stringify(t.body);else{const e=await this.walletClient.encrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t.recipient,plaintext:Ct("string"==typeof t.body?t.body:JSON.stringify(t.body),"utf8")},this.originator);s=JSON.stringify({encryptedMessage:Dt(e.ciphertext)})}const n={message:{...t,messageId:r,body:s},...null!=i&&{payment:i}};try{const i=e??await this.resolveHostForRecipient(t.recipient);if(qs("[MB CLIENT] Sending HTTP request to:",`${i}/sendMessage`),qs("[MB CLIENT] Request Body:",JSON.stringify(n,null,2)),null==this.myIdentityKey||""===this.myIdentityKey)try{const t=await this.walletClient.getPublicKey({identityKey:!0},this.originator);this.myIdentityKey=t.publicKey,qs(`[MB CLIENT] Fetched identity key before sending request: ${this.myIdentityKey}`)}catch(t){throw Ks("[MB CLIENT ERROR] Failed to fetch identity key:",t),new Error("Identity key retrieval failed")}const s=await this.authFetch.fetch(`${i}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(s.bodyUsed)throw new Error("[MB CLIENT ERROR] Response body has already been used!");const a=await s.json();if(qs("[MB CLIENT] Raw Response Body:",a),!s.ok)throw Ks(`[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 Ks(`[MB CLIENT ERROR] Server returned an error: ${String(a.description)}`),new Error(a.description??"Unknown error from server.");return qs("[MB CLIENT] Message successfully sent."),{...a,messageId:r}}catch(t){Ks("[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){qs("[MB CLIENT] Starting anointHost...");try{if(!t.startsWith("http"))throw new Error("Invalid host URL");const e=await this.getIdentityKey();qs("[MB CLIENT] Fields - Identity:",e,"Host:",t);const i=[Ct(e,"hex"),Ct(t,"utf8")],r=new yi(this.walletClient,this.originator);qs("Fields:",i.map((t=>Tt(t)))),qs("ProtocolID:",[1,"messagebox advertisement"]),qs("KeyID:","1"),qs("SignAs:","self"),qs("anyoneCanSpend:",!1),qs("forSelf:",!0);const s=await r.lock(i,[1,"messagebox advertisement"],"1","anyone",!0);qs("[MB CLIENT] PushDrop script:",s.toASM());const{tx:n,txid:a}=await this.walletClient.createAction({description:"Anoint host for overlay routing",outputs:[{basket:"overlay advertisements",lockingScript:s.toHex(),satoshis:1,outputDescription:"Overlay advertisement output"}],options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1}},this.originator);if(qs("[MB CLIENT] Transaction created:",a),void 0!==n){const t=new yr(["tm_messagebox"],{networkPreset:this.networkPreset}),e=await t.broadcast(Li.fromAtomicBEEF(n));if(qs("[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 Ks("[MB CLIENT ERROR] anointHost threw:",t),t}}async revokeHostAdvertisement(t){qs("[MB CLIENT] Starting revokeHost...");const e=`${t.txid}.${t.outputIndex}`;try{const{signableTransaction:i}=await this.walletClient.createAction({description:"Revoke MessageBox host advertisement",inputBEEF:t.beef,inputs:[{outpoint:e,unlockingScriptLength:73,inputDescription:"Revoking host advertisement token"}]},this.originator);if(void 0===i)throw new Error("Failed to create signable transaction.");const r=Li.fromBEEF(i.tx),s=new yi(this.walletClient,this.originator),n=await s.unlock([1,"messagebox advertisement"],"1","anyone","all",!1,t.outputIndex,t.lockingScript),a=await n.sign(r,t.outputIndex),{tx:o}=await this.walletClient.signAction({reference:i.reference,spends:{[t.outputIndex]:{unlockingScript:a.toHex()}},options:{acceptDelayedBroadcast:!1}},this.originator);if(void 0===o)throw new Error("Failed to finalize the transaction signature.");const c=new yr(["tm_messagebox"],{networkPreset:this.networkPreset}),h=await c.broadcast(Li.fromAtomicBEEF(o));if(qs("[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 Ks("[MB CLIENT ERROR] revokeHost threw:",t),t}}async listMessages({messageBox:t,host:e,acceptPayments:i}){if("boolean"!=typeof i&&(i=!0),""===t.trim())throw new Error("MessageBox cannot be empty");let r=null!=e?[e]:[];if(0===r.length){const t=await this.queryAdvertisements(await this.getIdentityKey(),void 0);r=Array.from(new Set([this.host,...t.map((t=>t.host))]))}const s=await Promise.allSettled(r.map((async e=>{try{qs(`[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 qs(`[MB CLIENT DEBUG] listMessages failed for ${e}:`,t),t}}))),n=[],a=[];for(const t of s)"fulfilled"===t.status?n.push(t.value):a.push(t.reason);if(0===n.length)throw new Error("Failed to retrieve messages from any host");const o=new Map;for(const t of n)for(const e of t)o.has(e.messageId)||o.set(e.messageId,e);if(0===o.size)return[];const c=Array.from(o.values());for(const t of c)try{const e="string"==typeof t.body?this.tryParse(t.body):t.body;let r,s=e;if(null!=e&&"object"==typeof e&&"message"in e){const t=e.message;s="string"==typeof t?this.tryParse(t):t,r=e.payment}if(i&&null!=r?.tx&&null!=r.outputs)try{qs(`[MB CLIENT] Processing recipient payment in message from ${String(t.sender)}…`);const e=r.outputs.filter((t=>"wallet payment"===t.protocol));e.length>0?(qs(`[MB CLIENT] Internalizing ${e.length} recipient payment output(s)…`),(await this.walletClient.internalizeAction({tx:r.tx,outputs:e,description:r.description??"MessageBox recipient payment"},this.originator)).accepted?qs("[MB CLIENT] Successfully internalized recipient payment"):Us("[MB CLIENT] Recipient payment internalization was not accepted")):qs("[MB CLIENT] No wallet payment outputs found in payment data")}catch(t){Ks("[MB CLIENT ERROR] Failed to internalize recipient payment:",t)}if(null!=s&&"object"==typeof s&&"string"==typeof s.encryptedMessage){qs(`[MB CLIENT] Decrypting message from ${String(t.sender)}…`);const e=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t.sender,ciphertext:Ct(s.encryptedMessage,"base64")},this.originator),i=Lt(e.plaintext);t.body=this.tryParse(i)}else t.body=s??e}catch(e){Ks("[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 listMessagesLite({messageBox:t,host:e}){const i=await this.authFetch.fetch(`${e}/listMessages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageBox:t})}),r=await i.json();if("error"===r.status)throw new Error(r.description??"Unknown server error");const s=r.messages,n=t=>{try{return JSON.parse(t)}catch{return t}};for(const t of s)try{const e="string"==typeof t.body?n(t.body):t.body;let i=e;if(null!=e&&"object"==typeof e&&"message"in e){const t=e.message;i="string"==typeof t?n(t):t}if(null!=i&&"object"==typeof i&&"string"==typeof i.encryptedMessage){const e=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t.sender,ciphertext:Ct(i.encryptedMessage,"base64")}),r=Lt(e.plaintext);t.body=n(r)}else t.body=i??e}catch(e){Ks("[MB CLIENT ERROR] Failed to parse or decrypt message in list:",e),t.body="[Error: Failed to decrypt or parse message]"}return s}tryParse(t){try{return JSON.parse(t)}catch{return t}}async acknowledgeNotification(t){await this.acknowledgeMessage({messageIds:[t.messageId]});const e="string"==typeof t.body?this.tryParse(t.body):t.body;let i;if(null!=e&&"object"==typeof e&&"message"in e&&(i=e.payment),null!=i?.tx&&null!=i.outputs)try{qs(`[MB CLIENT] Processing recipient payment in message from ${String(t.sender)}…`);const e=i.outputs.filter((t=>"wallet payment"===t.protocol));return e.length<1?(qs("[MB CLIENT] No wallet payment outputs found in payment data"),!1):(qs(`[MB CLIENT] Internalizing ${e.length} recipient payment output(s)…`),(await this.walletClient.internalizeAction({tx:i.tx,outputs:e,description:i.description??"MessageBox recipient payment"})).accepted?(qs("[MB CLIENT] Successfully internalized recipient payment"),!0):(Us("[MB CLIENT] Recipient payment internalization was not accepted"),!1))}catch(t){return Ks("[MB CLIENT ERROR] Failed to internalize recipient payment:",t),!1}return!1}async acknowledgeMessage({messageIds:t,host:e}){if(!Array.isArray(t)||0===t.length)throw new Error("Message IDs array cannot be empty");qs(`[MB CLIENT] Acknowledging messages ${JSON.stringify(t)}…`);let i=null!=e?[e]:[];if(0===i.length){const t=await this.getIdentityKey(),e=await this.queryAdvertisements(t,void 0);i=Array.from(new Set([this.host,...e.map((t=>t.host))]))}const r=await Promise.allSettled(i.map((async e=>{try{const i=await this.authFetch.fetch(`${e}/acknowledgeMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageIds:t})});if(!i.ok)throw new Error(`HTTP ${i.status}`);const r=await i.json();if("error"===r.status)throw new Error(r.description);return qs(`[MB CLIENT] Acknowledged on ${e}`),r.status}catch(t){return Us(`[MB CLIENT WARN] acknowledgeMessage failed for ${e}:`,t),null}}))),s=r.filter((t=>"fulfilled"===t.status)),n=s.find((t=>null!=t.value))?.value;if(null!=n)return n;const a=[];for(const t of r)"rejected"===t.status&&a.push(t.reason);throw new Error(`Failed to acknowledge messages on all hosts: ${a.map((t=>String(t))).join("; ")}`)}async setMessageBoxPermission(t,e){const i=e??this.host;qs("[MB CLIENT] Setting messageBox permission...");const r=await this.authFetch.fetch(`${i}/permissions/set`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageBox:t.messageBox,recipientFee:t.recipientFee,...null!=t.sender&&{sender:t.sender}})});if(!r.ok){const t=await r.json().catch((()=>({})));throw new Error(`Failed to set permission: HTTP ${r.status} - ${""!==String(t.description)?String(t.description):r.statusText}`)}const{status:s,description:n}=await r.json();if("error"===s)throw new Error(n??"Failed to set permission")}async getMessageBoxPermission(t,e){const i=e??await this.resolveHostForRecipient(t.recipient),r=new URLSearchParams({recipient:t.recipient,messageBox:t.messageBox,...null!=t.sender&&{sender:t.sender}});qs("[MB CLIENT] Getting messageBox permission...");const s=await this.authFetch.fetch(`${i}/permissions/get?${r.toString()}`,{method:"GET"});if(!s.ok){const t=await s.json().catch((()=>({})));throw new Error(`Failed to get permission: HTTP ${s.status} - ${""!==String(t.description)?String(t.description):s.statusText}`)}const n=await s.json();if("error"===n.status)throw new Error(n.description??"Failed to get permission");return n.permission}async getMessageBoxQuote(t,e){const i=e??await this.resolveHostForRecipient(t.recipient),r=new URLSearchParams({recipient:t.recipient,messageBox:t.messageBox});qs("[MB CLIENT] Getting messageBox quote...");const s=await this.authFetch.fetch(`${i}/permissions/quote?${r.toString()}`,{method:"GET"});if(!s.ok){const t=await s.json().catch((()=>({})));throw new Error(`Failed to get quote: HTTP ${s.status} - ${String(t.description)??s.statusText}`)}const{status:n,description:a,quote:o}=await s.json();if("error"===n)throw new Error(a??"Failed to get quote");const c=s.headers.get("x-bsv-auth-identity-key");if(null==c)throw new Error("Failed to get quote: Delivery agent did not provide their identity key");return{recipientFee:o.recipientFee,deliveryFee:o.deliveryFee,deliveryAgentIdentityKey:c}}async listMessageBoxPermissions(t,e){const i=e??this.host,r=new URLSearchParams;null!=t?.messageBox&&r.set("message_box",t.messageBox),void 0!==t?.limit&&r.set("limit",t.limit.toString()),void 0!==t?.offset&&r.set("offset",t.offset.toString()),qs("[MB CLIENT] Listing messageBox permissions with params:",r.toString());const s=await this.authFetch.fetch(`${i}/permissions/list?${r.toString()}`,{method:"GET"});if(!s.ok){const t=await s.json().catch((()=>({})));throw new Error(`Failed to list permissions: HTTP ${s.status} - ${""!==String(t.description)?String(t.description):s.statusText}`)}const n=await s.json();if("error"===n.status)throw new Error(n.description??"Failed to list permissions");return n.permissions.map((t=>({sender:t.sender,messageBox:t.message_box,recipientFee:t.recipient_fee,status:$s.getStatusFromFee(t.recipient_fee),createdAt:t.created_at,updatedAt:t.updated_at})))}async allowNotificationsFromPeer(t,e=0,i){await this.setMessageBoxPermission({messageBox:"notifications",sender:t,recipientFee:e},i)}async denyNotificationsFromPeer(t,e){await this.setMessageBoxPermission({messageBox:"notifications",sender:t,recipientFee:-1},e)}async checkPeerNotificationStatus(t,e){const i=await this.getIdentityKey();return await this.getMessageBoxPermission({recipient:i,messageBox:"notifications",sender:t},e)}async listPeerNotifications(t){return await this.listMessageBoxPermissions({messageBox:"notifications"},t)}async sendNotification(t,e,i){return await this.assertInitialized(),await this.sendMessage({recipient:t,messageBox:"notifications",body:e,checkPermissions:!0},i)}async registerDevice(t,e){if(null==t.fcmToken||""===t.fcmToken.trim())throw new Error("fcmToken is required and must be a non-empty string");if(null!=t.platform&&!["ios","android","web"].includes(t.platform))throw new Error("platform must be one of: ios, android, web");const i=e??this.host;qs("[MB CLIENT] Registering device for FCM notifications...");const r=await this.authFetch.fetch(`${i}/registerDevice`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fcmToken:t.fcmToken.trim(),deviceId:t.deviceId?.trim()??void 0,platform:t.platform??void 0})});if(!r.ok){const t=await r.json().catch((()=>({}))),e=String(t.description)??r.statusText;throw new Error(`Failed to register device: HTTP ${r.status} - ${e}`)}const s=await r.json();if("error"===s.status)throw new Error(s.description??"Failed to register device");return qs("[MB CLIENT] Device registered successfully"),{status:s.status,message:s.message,deviceId:s.deviceId}}async listRegisteredDevices(t){const e=t??this.host;qs("[MB CLIENT] Listing registered devices...");const i=await this.authFetch.fetch(`${e}/devices`,{method:"GET"});if(!i.ok){const t=await i.json().catch((()=>({}))),e=String(t.description)??i.statusText;throw new Error(`Failed to list devices: HTTP ${i.status} - ${e}`)}const r=await i.json();if("error"===r.status)throw new Error(r.description??"Failed to list devices");return qs(`[MB CLIENT] Found ${r.devices.length} registered devices`),r.devices}static getStatusFromFee(t){return-1===t?"blocked":0===t?"always_allow":"payment_required"}async createMessagePayment(t,e,i="MessageBox delivery payment"){if(e.recipientFee<=0&&e.deliveryFee<=0)throw new Error("No payment required");qs(`[MB CLIENT] Creating payment transaction for ${e.recipientFee} sats (delivery: ${e.deliveryFee}, recipient: ${e.recipientFee})`);const r=[],s=[],n=await this.getIdentityKey();let a=0;if(e.deliveryFee>0){const t=Dt(xe(32)),i=Dt(xe(32)),{publicKey:o}=await this.walletClient.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${t} ${i}`,counterparty:e.deliveryAgentIdentityKey},this.originator),c=(new bi).lock(_e.fromString(o).toAddress()).toHex();s.push({satoshis:e.deliveryFee,lockingScript:c,outputDescription:"MessageBox server delivery fee",customInstructions:JSON.stringify({derivationPrefix:t,derivationSuffix:i,recipientIdentityKey:e.deliveryAgentIdentityKey})}),r.push({outputIndex:a++,protocol:"wallet payment",paymentRemittance:{derivationPrefix:t,derivationSuffix:i,senderIdentityKey:n}})}if(e.recipientFee>0){const i=Dt(xe(32)),n=Dt(xe(32)),o=new Fi("anyone"),{publicKey:c}=await o.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${i} ${n}`,counterparty:t});if(null==c||""===c.trim())throw new Error("Failed to derive recipient's public key");const h=(new bi).lock(_e.fromString(c).toAddress()).toHex();s.push({satoshis:e.recipientFee,lockingScript:h,outputDescription:"Recipient message fee",customInstructions:JSON.stringify({derivationPrefix:i,derivationSuffix:n,recipientIdentityKey:t})}),r.push({outputIndex:a++,protocol:"wallet payment",paymentRemittance:{derivationPrefix:i,derivationSuffix:n,senderIdentityKey:(await o.getPublicKey({identityKey:!0})).publicKey}})}const{tx:o}=await this.walletClient.createAction({description:i,outputs:s,options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1}},this.originator);if(null==o)throw new Error("Failed to create payment transaction");return{tx:o,outputs:r,description:i}}}function js(t){try{return"string"==typeof t?JSON.parse(t):t}catch(e){return Ks("[PP CLIENT] Failed to parse input in safeParse:",t),{}}}const zs="payment_inbox";class Ws extends $s{peerPayWalletClient;_authFetchInstance;constructor(t){const{messageBoxHost:e="https://messagebox.babbage.systems",walletClient:i,enableLogging:r=!1,originator:s}=t;super({host:e,walletClient:i,enableLogging:r,originator:s}),this.peerPayWalletClient=i,this.originator=s}get authFetchInstance(){return null!==this._authFetchInstance&&void 0!==this._authFetchInstance||(this._authFetchInstance=new hr(this.peerPayWalletClient,void 0,void 0,this.originator)),this._authFetchInstance}async createPaymentToken(t){if(t.amount<=0)throw new Error("Invalid payment details: recipient and valid amount are required");const e=await ir(this.peerPayWalletClient),i=await ir(this.peerPayWalletClient);qs(`[PP CLIENT] Derivation Prefix: ${e}`),qs(`[PP CLIENT] Derivation Suffix: ${i}`);const{publicKey:r}=await this.peerPayWalletClient.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${e} ${i}`,counterparty:t.recipient},this.originator);if(qs(`[PP CLIENT] Derived Public Key: ${r}`),null==r||""===r.trim())throw new Error("Failed to derive recipient’s public key");const s=(new bi).lock(_e.fromString(r).toAddress()).toHex();qs(`[PP CLIENT] Locking Script: ${s}`);const n=await this.peerPayWalletClient.createAction({description:"PeerPay payment",labels:["peerpay"],outputs:[{satoshis:t.amount,lockingScript:s,customInstructions:JSON.stringify({derivationPrefix:e,derivationSuffix:i,payee:t.recipient}),outputDescription:"Payment for PeerPay transaction"}],options:{randomizeOutputs:!1}},this.originator);if(void 0===n.tx)throw new Error("Transaction creation failed!");return qs("[PP CLIENT] Payment Action:",n),{customInstructions:{derivationPrefix:e,derivationSuffix:i},transaction:n.tx,amount:t.amount}}async sendPayment(t,e){if(null==t.recipient||""===t.recipient.trim()||t.amount<=0)throw new Error("Invalid payment details: recipient and valid amount are required");const i=await this.createPaymentToken(t);await this.sendMessage({recipient:t.recipient,messageBox:zs,body:JSON.stringify(i)},e)}async sendLivePayment(t,e){const i=await this.createPaymentToken(t);try{await this.sendLiveMessage({recipient:t.recipient,messageBox:zs,body:JSON.stringify(i)},e)}catch(r){Us("[PP CLIENT] sendLiveMessage failed, falling back to HTTP:",r),await this.sendMessage({recipient:t.recipient,messageBox:zs,body:JSON.stringify(i)},e)}}async listenForLivePayments({onPayment:t,overrideHost:e}){await this.listenForLiveMessages({messageBox:zs,overrideHost:e,onMessage:e=>{qs("[MB CLIENT] Received Live Payment:",e);const i={messageId:e.messageId,sender:e.sender,token:js(e.body)};qs("[PP CLIENT] Converted PeerMessage to IncomingPayment:",i),t(i)}})}async acceptPayment(t){try{qs(`[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"}],labels:["peerpay"],description:"PeerPay Payment"},this.originator);return qs(`[PP CLIENT] Payment internalized successfully: ${JSON.stringify(e,null,2)}`),qs(`[PP CLIENT] Acknowledging payment with messageId: ${t.messageId}`),await this.acknowledgeMessage({messageIds:[t.messageId]}),{payment:t,paymentResult:e}}catch(t){return Ks(`[PP CLIENT] Error accepting payment: ${String(t)}`),"Unable to receive payment!"}}async rejectPayment(t){if(qs(`[PP CLIENT] Rejecting payment: ${JSON.stringify(t,null,2)}`),t.token.amount-1e3<1e3){qs("[PP CLIENT] Payment amount too small after fee, just acknowledging.");try{qs(`[PP CLIENT] Attempting to acknowledge message ${t.messageId}...`),null!==this.authFetch&&void 0!==this.authFetch||Us("[PP CLIENT] Warning: authFetch is undefined! Ensure PeerPayClient is initialized correctly."),qs("[PP CLIENT] authFetch instance:",this.authFetch),qs(`[PP CLIENT] Acknowledgment response: ${await this.acknowledgeMessage({messageIds:[t.messageId]})}`)}catch(t){if(null==t||"object"!=typeof t||!("message"in t)||"string"!=typeof t.message||!t.message.includes("401"))throw Ks(`[PP CLIENT] Error acknowledging message: ${t.message}`),t;Us(`[PP CLIENT] Authentication issue while acknowledging: ${t.message}`)}}else{qs("[PP CLIENT] Accepting payment before refunding..."),await this.acceptPayment(t),qs(`[PP CLIENT] Sending refund of ${t.token.amount-1e3} to ${t.sender}...`),await this.sendPayment({recipient:t.sender,amount:t.token.amount-1e3}),qs("[PP CLIENT] Payment successfully rejected and refunded.");try{qs(`[PP CLIENT] Acknowledging message ${t.messageId} after refunding...`),await this.acknowledgeMessage({messageIds:[t.messageId]}),qs("[PP CLIENT] Acknowledgment after refund successful.")}catch(t){Ks(`[PP CLIENT] Error acknowledging message after refund: ${t.message}`)}}}async listIncomingPayments(t){return(await this.listMessages({messageBox:zs,host:t})).map((t=>{const e=js(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:()=>$s,PeerPayClient:()=>Ws,STANDARD_PAYMENT_MESSAGEBOX:()=>zs});var i={};t.r(i),t.d(i,{Decoder:()=>Ns,Encoder:()=>Os,PacketType:()=>Ps,protocol:()=>_s});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 s=t.length>0?t.length:1;for(let e=s-1;e>=0;e--){const s=void 0===t[e]?0:t[e];i=i<<r.WORD_SIZE_BIGINT|BigInt(s&Number(r.WORD_MASK))}this._magnitude=i,this._sign=e,this._nominalWordLength=s,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,s=i;if("le"!==e&&"be"!==e||(s=e,r=10),"number"!=typeof t)if(Array.isArray(t))this.initArray(t,s);else if("string"==typeof t){"hex"===r&&(r=16),this.assert("number"==typeof r&&r===(0|r)&&r>=2&&r<=36,"Base must be an integer between 2 and 36");const e=t.toString().replace(/\s+/g,"");let i=0,n=0;e.startsWith("-")?(i++,n=1):e.startsWith("+")&&i++;const a=e.substring(i);if(0===a.length)return this._initializeState(0n,1===n&&e.startsWith("-")?1:0),void this.normSign();if(16===r){let t;if("le"===s){const t=[];let e=a;e.length%2!=0&&(e="0"+e);for(let i=0;i<e.length;i+=2){const r=e.substring(i,i+2),s=parseInt(r,16);if(isNaN(s))throw new Error("Invalid character in "+e);t.push(s)}return this.initArray(t,"le"),this._sign=n,void this.normSign()}try{t=BigInt("0x"+a)}catch(t){throw new Error("Invalid character in "+a)}this._initializeState(t,n),this.normSign()}else try{if(this._parseBaseString(a,r),this._sign=n,this.normSign(),"le"===s){const t=this._sign;this.initArray(this.toArray("be"),"le"),this._sign=t,this.normSign()}}catch(t){const e=t;if(e.message.includes("Invalid character in string")||e.message.includes("Invalid digit for base")||e.message.startsWith("Invalid character:"))throw new Error("Invalid character");throw e}}else 0!==t?this.assert(!1,"Unsupported input type for BigNumber constructor"):this._initializeState(0n,0);else this.initNumber(t,s)}_bigIntToStringInBase(t,e){if(0n===t)return"0";if(e<2||e>36)throw new Error("Base must be between 2 and 36");let i="",r=t>0n?t:-t;const s=BigInt(e);for(;r>0n;)i="0123456789abcdefghijklmnopqrstuvwxyz"[Number(r%s)]+i,r/=s;return i}_parseBaseString(t,e){if(0===t.length)return this._magnitude=0n,void this._finishInitialization();this._magnitude=0n;const i=BigInt(e);let s=r.groupSizes[e],n=BigInt(r.groupBases[e]);0!==s&&0n!==n||(s=Math.floor(Math.log(67108863)/Math.log(e)),0===s&&(s=1),n=i**BigInt(s));let a=0;const o=t.length;let c=o%s;if(0===c&&o>0&&(c=s),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+s),r=BigInt(this._parseBaseWord(i,e));this._magnitude=this._magnitude*n+r,a+=s}this._finishInitialization()}_parseBaseWord(t,e){let i=0;for(let r=0;r<t.length;r++){const s=t.charCodeAt(r);let n;if(s>=48&&s<=57)n=s-48;else if(s>=65&&s<=90)n=s-65+10;else{if(!(s>=97&&s<=122))throw new Error("Invalid character: "+t[r]);n=s-97+10}if(n>=e)throw new Error("Invalid character");i=i*e+n}return i}_initializeState(t,e){this._magnitude=t,this._sign=0n===t?0:e,this._finishInitialization()}_finishInitialization(){if(0n===this._magnitude)this._nominalWordLength=1,this._sign=0;else{const t=this._magnitude.toString(2).length;this._nominalWordLength=Math.max(1,Math.ceil(t/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],s=BigInt(r.groupBases[t]);0!==i&&0n!==s||(i=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(t)),0===i&&(i=1),s=BigInt(t)**BigInt(i));let n="",a=this._magnitude;for(;a>0n;){const e=a%s;a/=s;const o=this._bigIntToStringInBase(e,t);if(a>0n){const t=i-o.length;n=t>0&&t<r.zeros.length?r.zeros[t]+o+n:t>0?"0".repeat(t)+o+n:o+n}else n=o+n}if(e>0)for(;n.length<e;)n="0"+n;return(1===this._sign?"-":"")+n}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 s=e?1:-1;for(let e=0;e<t.length;++e){if(0n===i&&r>=0&&r<t.length)t[r]=0;else{if(!(r>=0&&r<t.length))break;t[r]=Number(0xffn&i)}i>>=8n,r+=s}}toArray(t="be",e){this.strip();const i=this.byteLength(),r=e??Math.max(1,i);this.assert(i<=r,"byte array longer than desired length"),this.assert(r>0,"Requested array length <= 0");const s=new Array(r).fill(0);return 0n===this._magnitude&&r>0?s:0n===this._magnitude&&0===r?[]:(this.toArrayLikeGeneric(s,"le"===t),s)}bitLength(){return 0n===this._magnitude?0:this._magnitude.toString(2).length}static toBitArray(t){const e=t.bitLength();if(0===e)return[];const i=new Array(e),r=t._magnitude;for(let t=0;t<e;t++)i[t]=0n!==(r>>BigInt(t)&1n)?1:0;return i}toBitArray(){return 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 s=new r(0n);return s._initializeState(i,0),s}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),s=new r(0n);return s._setValueFromSigned(t),s}return this.clone()}isNeg(){return 1===this._sign&&0n!==this._magnitude}neg(){return this.clone().ineg()}ineg(){return 0n!==this._magnitude&&(this._sign=1===this._sign?0:1),this}_iuop(t,e){const i=e(this._magnitude,t._magnitude),r=e===((t,e)=>t^e);let s=this._nominalWordLength;return r&&(s=Math.max(this.length,t.length)),this._magnitude=i,this._finishInitialization(),r&&(this._nominalWordLength=Math.max(this._nominalWordLength,s)),this.strip()}iuor(t){return this._iuop(t,((t,e)=>t|e))}iuand(t){return this._iuop(t,((t,e)=>t&e))}iuxor(t){return this._iuop(t,((t,e)=>t^e))}_iop(t,e){return this.assert(0===this._sign&&0===t._sign),this._iuop(t,e)}ior(t){return this._iop(t,((t,e)=>t|e))}iand(t){return this._iop(t,((t,e)=>t&e))}ixor(t){return this._iop(t,((t,e)=>t^e))}_uop_new(t,e){return this.length>=t.length?this.clone()[e](t):t.clone()[e](this)}or(t){return this.assert(0===this._sign&&0===t._sign),this._uop_new(t,"iuor")}uor(t){return this._uop_new(t,"iuor")}and(t){return this.assert(0===this._sign&&0===t._sign),this._uop_new(t,"iuand")}uand(t){return this._uop_new(t,"iuand")}xor(t){return this.assert(0===this._sign&&0===t._sign),this._uop_new(t,"iuxor")}uxor(t){return this._uop_new(t,"iuxor")}inotn(t){this.assert("number"==typeof t&&t>=0);const e=(1n<<BigInt(t))-1n;this._magnitude=~this._magnitude&e;const i=0===t?1:Math.ceil(t/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 s=Math.floor(t/r.wordSize)+1;return this._nominalWordLength=Math.max(this._nominalWordLength,s),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(),s=t.clone(),n=i.isNeg(),a=s.isOdd();for(n&&i.ineg();!s.isZero();)s.isOdd()&&e.imul(i),i.isqr(),s.iushrn(1);return n&&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 s=0===t?1:Math.max(1,Math.ceil(t/r.wordSize));return this._nominalWordLength=s,this._finishInitialization(),this._nominalWordLength=Math.max(this._nominalWordLength,s),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 s=this._getSignedValue(),n=t._getSignedValue();let a=null,o=null;"mod"!==e&&(a=s/n),"div"!==e&&(o=s%n,!0===i&&o<0n&&(o+=n<0n?-n:n));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 s=e/i;const n=e%i;if(0n===n){const t=new r(0n);return t._setValueFromSigned(s),t}2n*(n<0n?-n:n)>=(i<0n?-i:i)&&(e>0n&&i>0n||e<0n&&i<0n?s+=1n:s-=1n);const a=new r(0n);return a._setValueFromSigned(s),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,s=1n,n=0n,a=0n,o=1n;for(;0n!==i;){const t=e/i;let r=i;i=e%i,e=r,r=n,n=s-t*n,s=r,r=o,o=a-t*o,a=r}const c=new r(0n);c._setValueFromSigned(s);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 s=new r(0n);return s._initializeState(e,0),s}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,s="";if("little"===e){const e=t.length-1;let r=t[e];128&r&&(i=1,r&=127),s+=(r<16?"0":"")+r.toString(16);for(let i=e-1;i>=0;i--){const e=t[i];s+=(e<16?"0":"")+e.toString(16)}}else{let e=t[0];128&e&&(i=1,e&=127),s+=(e<16?"0":"")+e.toString(16);for(let e=1;e<t.length;e++){const i=t[e];s+=(i<16?"0":"")+i.toString(16)}}const n=""===s?0n:BigInt("0x"+s),a=new r(0n);return a._initializeState(n,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,s=8388607&t,n=!!(8388608&t);if(e&&n)throw new Error("negative bit set");if(0===i&&0===s){if(n&&e)throw new Error("negative bit set for zero value");return new r(0n)}const a=new r(s);return i<=3?a.iushrn(8*(3-i)):a.iushln(8*(i-3)),n&&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 s,n=i.length;if(0!==n||e.isZero()||(i=[0],n=1),e.isZero()&&(n=0,i=[]),0===n)s=0;else if(n<=3){s=0;for(let t=0;t<n;t++)s=s<<8|i[t]}else s=i[0]<<16|i[1]<<8|i[2];8388608&s&&n<=255&&(s>>>=8,n++);let a=n<<24|s;return t&&(a|=8388608),a>>>0}static fromScriptNum(t,e=!1,i){if(void 0!==i&&t.length>i)throw new Error("script number overflow");if(0===t.length)return new 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,s=1n,n=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&s)&&(s+=a),s>>=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&n)&&(n+=a),n>>=1n}e>=i?(e-=i,s-=n):(i-=e,n-=s)}let o;if(1n===e)o=s;else if(1n===i)o=n;else if(0n===e&&1n===i)o=n;else{if(0n!==i||1n!==e)throw new Error("_invmp: GCD is not 1, inverse does not exist. aVal="+e+", bVal="+i);o=s}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 s{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 n extends s{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(t,e){const i=4194303,r=t.words,s=t.length,n=Math.min(s,9),a=new Array(n+(s>9?1:0)).fill(0);for(let t=0;t<n;t++)a[t]=r[t];let o=n;if(s<=9){const i=new Array(o);for(let t=0;t<o;++t)i[t]=a[t];return e.words=i,void(t.words=[0])}let c=r[9];a[o++]=c&i;const h=new Array(o);for(let t=0;t<o;++t)h[t]=a[t];e.words=h;const d=new Array(Math.max(1,s-9)).fill(0);let u=0;for(let t=10;t<s;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,s=new Array(r).fill(0);for(let t=0;t<i;t++)s[t]=e[t];let n=0;for(let t=0;t<r;t++){const e=0|s[t];n+=977*e,s[t]=67108863&n,n=64*e+(n/67108864|0)}return t.words=s,t}}class a{prime;m;constructor(t){if("k256"===t){const t=new n;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 s=0;for(;!i.isZero()&&0===i.andln(1);)s++,i.iushrn(1);this.assert(!i.isZero());const n=new r(1).toRed(this),a=n.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=s;for(;0!==l.cmp(n);){let t=l,e=0;for(;0!==t.cmp(n);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 s=2;for(;s<i.length;s++)i[s]=this.mul(i[s-1],t);let n=i[0],a=0,o=0,c=e.bitLength()%26;for(0===c&&(c=26),s=e.length-1;s>=0;s--){const t=e.words[s];for(let e=c-1;e>=0;e--){const r=t>>e&1;n!==i[0]&&(n=this.sqr(n)),0!==r||0!==a?(a<<=1,a|=r,o++,(4===o||0===s&&0===e)&&(n=this.mul(n,i[a]),o=0,a=0)):o=0}c=26}return n}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),s=i.isub(r).iushrn(this.shift);let n=s;return s.cmp(this.m)>=0?n=s.isub(this.m):s.cmpn(0)<0&&(n=s.iadd(this.m)),n.forceRed(this)}mul(t,e){if(t.isZero()||e.isZero())return new r(0).forceRed(this);const i=t.mul(e),s=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=i.isub(s).iushrn(this.shift);let a=n;return n.cmp(this.m)>=0?a=n.isub(this.m):n.cmpn(0)<0&&(a=n.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 be,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 fe(null,null);const t=this.z.redInvm(),e=t.redSqr(),i=this.x.redMul(e),r=this.y.redMul(e).redMul(t);return new fe(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),s=t.x.redMul(i),n=this.y.redMul(e.redMul(t.z)),a=t.y.redMul(i.redMul(this.z)),o=r.redSub(s),c=n.redSub(a);if(0===o.cmpn(0))return 0!==c.cmpn(0)?new 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(n.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),s=this.y,n=t.y.redMul(e).redMul(this.z),a=i.redSub(r),o=s.redSub(n);if(0===a.cmpn(0))return 0!==o.cmpn(0)?new 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(s.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(),s=this.y.redSqr(),n=s.redSqr();let a=this.x.redAdd(s).redSqr().redISub(r).redISub(n);a=a.redIAdd(a);const o=r.redAdd(r).redIAdd(r),c=o.redSqr().redISub(a).redISub(a);let h=n.redIAdd(n);h=h.redIAdd(h),h=h.redIAdd(h),t=c,e=o.redMul(a.redISub(c)).redISub(h),i=this.y.redAdd(this.y)}else{const r=this.x.redSqr(),s=this.y.redSqr(),n=s.redSqr();let a=this.x.redAdd(s).redSqr().redISub(r).redISub(n);a=a.redIAdd(a);const o=r.redAdd(r).redIAdd(r),c=o.redSqr();let h=n.redIAdd(n);h=h.redIAdd(h),h=h.redIAdd(h),t=c.redISub(a).redISub(a),e=o.redMul(a.redISub(t)).redISub(h),i=this.y.redMul(this.z),i=i.redIAdd(i)}return new 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),s=i.redMul(t.z);return 0===this.y.redMul(s).redISub(t.y.redMul(r)).cmpn(0)}eqXToP(t){const e=this.z.redSqr(),i=t.toRed(this.curve?.red).redMul(e);if(0===this.x.cmp(i))return!0;const r=t.clone();if(null===this.curve||null==this.curve.redN)throw new Error("Curve or redN is not initialized.");const s=this.curve.redN.redMul(e);for(;r.cmp(this.curve.p)<0;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(i.redIAdd(s),0===this.x.cmp(i))return!0}return!1}inspect(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"}isInfinity(){return 0===this.z.cmpn(0)}}const 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 s=i-0;d(s%4==0);const n=new Array(s/4);for(let e=0,i=0;e<n.length;e++,i+=4){let s;s="big"===r?t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3]:t[i+3]<<24|t[i+2]<<16|t[i+1]<<8|t[i],n[e]=s>>>0}return n}(t,0,t.length-e,this.endian);for(let e=0;e<t.length;e+=this._delta32)this._update(t,e)}return this}digest(){return this.update(this._pad()),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 s,n;for(r[0]=128,s=1;s<i;s++)r[s]=0;if(t<<=3,"big"===this.endian){for(n=8;n<this.padLength;n++)r[s++]=0;r[s++]=0,r[s++]=0,r[s++]=0,r[s++]=0,r[s++]=t>>>24&255,r[s++]=t>>>16&255,r[s++]=t>>>8&255,r[s++]=255&t}else for(r[s++]=255&t,r[s++]=t>>>8&255,r[s++]=t>>>16&255,r[s++]=t>>>24&255,r[s++]=0,r[s++]=0,r[s++]=0,r[s++]=0,n=8;n<this.padLength;n++)r[s++]=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 s=t.charCodeAt(r);s<128?i[e++]=s:s<2048?(i[e++]=s>>6|192,i[e++]=63&s|128):l(t,r)?(s=65536+((1023&s)<<10)+(1023&t.charCodeAt(++r)),i[e++]=s>>18|240,i[e++]=s>>12&63|128,i[e++]=s>>6&63|128,i[e++]=63&s|128):(i[e++]=s>>12|224,i[e++]=s>>6&63|128,i[e++]=63&s|128)}}else{(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 s=0;s<t.length;s++){let n=t[s];"little"===e&&(n=p(n)),i+=7===(r=n.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){let e="";for(const i of t)e+=i.toString(16).padStart(2,"0");return e}function y(t,e){const i=new Array(4*t.length);for(let r=0,s=0;r<t.length;r++,s+=4){const n=t[r];"big"===e?(i[s]=n>>>24,i[s+1]=n>>>16&255,i[s+2]=n>>>8&255,i[s+3]=255&n):(i[s+3]=n>>>24,i[s+2]=n>>>16&255,i[s+1]=n>>>8&255,i[s]=255&n)}return i}function m(t,e){return t>>>e|t<<32-e}function w(t,e){return t<<e|t>>>32-e}function I(t,e){return t+e>>>0}function v(t,e,i){return t+e+i>>>0}function k(t,e,i,r){return t+e+i+r>>>0}function S(t,e,i,r,s){return t+e+i+r+s>>>0}function E(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?P(e,i,r):0}function _(t,e,i){return t&e^~t&i}function P(t,e,i){return t&e^t&i^e&i}function O(t){return m(t,2)^m(t,13)^m(t,22)}function x(t){return m(t,6)^m(t,11)^m(t,25)}function N(t){return m(t,17)^m(t,19)^t>>>10}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],T=[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],C=[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],R=[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 B(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 L(t){return t<=15?0:t<=31?1518500249:t<=47?1859775393:t<=63?2400959708:2840853838}function M(t){return t<=15?1352829926:t<=31?1548603684:t<=47?1836072691:t<=63?2053994217:0}class D 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],s=this.h[1],n=this.h[2],a=this.h[3],o=this.h[4],c=r,h=s,d=n,u=a,l=o;for(let f=0;f<80;f++)i=I(w(k(r,B(f,s,n,a),t[A[f]+e],L(f)),C[f]),o),r=o,o=a,a=w(n,10),n=s,s=i,i=I(w(k(c,B(79-f,h,d,u),t[T[f]+e],M(f)),R[f]),l),c=l,l=u,u=w(d,10),d=h,h=i;i=v(this.h[1],n,u),this.h[1]=v(this.h[2],a,l),this.h[2]=v(this.h[3],o,c),this.h[3]=v(this.h[4],r,h),this.h[4]=v(this.h[0],s,d),this.h[0]=i}_digest(){return y(this.h,"little")}_digestHex(){return b(this.h,"little")}}class F{h;constructor(){this.h=new It}update(t,e){const i=Uint8Array.from(f(t,e));return this.h.update(i),this}digest(){return Array.from(this.h.digest())}digestHex(){return g(this.h.digest())}}class V 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]=w(i[r-3]^i[r-8]^i[r-14]^i[r-16],1);let s=this.h[0],n=this.h[1],a=this.h[2],o=this.h[3],c=this.h[4];for(r=0;r<i.length;r++){const t=~~(r/20),e=S(w(s,5),E(t,n,a,o),c,i[r],this.k[t]);c=o,o=a,a=w(n,30),n=s,s=e}this.h[0]=I(this.h[0],s),this.h[1]=I(this.h[1],n),this.h[2]=I(this.h[2],a),this.h[3]=I(this.h[3],o),this.h[4]=I(this.h[4],c)}_digest(){return y(this.h,"big")}_digestHex(){return b(this.h,"big")}}class H{h;blockSize=64;outSize=32;constructor(t){const e=Uint8Array.from(f(t,"hex"));this.h=new At(vt,e)}update(t,e){return this.h.update(Uint8Array.from(f(t,e))),this}digest(){return Array.from(this.h.digest())}digestHex(){return g(this.h.digest())}}class q{h;blockSize=128;outSize=32;constructor(t){const e=Uint8Array.from(f(t,"hex"));this.h=new At(Nt,e)}update(t,e){return this.h.update(Uint8Array.from(f(t,e))),this}digest(){return Array.from(this.h.digest())}digestHex(){return g(this.h.digest())}}const U=(t,e)=>(new F).update(t,e).digest(),K=(t,e)=>{const i=(new F).update(t,e).digest();return(new F).update(i).digest()},$=(t,e)=>{const i=(new F).update(t,e).digest();return(new D).update(i).digest()},j=(t,e,i)=>new H(t).update(e,i).digest();function z(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, got ${t}`)}function W(t,...e){if(!((i=t)instanceof Uint8Array||ArrayBuffer.isView(i)&&"Uint8Array"===i.constructor.name))throw new Error("Uint8Array expected");var i;if(e.length>0&&!e.includes(t.length)){const i=e.join(",");throw new Error(`Uint8Array expected of length ${i}, got length=${t.length}`)}}function G(t,e=!0){if(!0===t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&!0===t.finished)throw new Error("Hash#digest() has already been called")}function X(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function J(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Y(t){return"string"==typeof t&&(t=function(t){if("string"!=typeof t)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(t))}(t)),W(t),t}class Z{}function Q(t){const e=e=>t().update(Y(e)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}const tt=BigInt(2**32-1),et=BigInt(32);function it(t,e=!1){return e?{h:Number(t&tt),l:Number(t>>et&tt)}:{h:0|Number(t>>et&tt),l:0|Number(t&tt)}}const rt=(t,e,i)=>t>>>i,st=(t,e,i)=>t<<32-i|e>>>i,nt=(t,e,i)=>t>>>i|e<<32-i,at=(t,e,i)=>t<<32-i|e>>>i,ot=(t,e,i)=>t<<64-i|e>>>i-32,ct=(t,e,i)=>t>>>i-32|e<<64-i;function ht(t,e,i,r){const s=(e>>>0)+(r>>>0);return{h:t+i+(s/2**32|0)|0,l:0|s}}const dt=(t,e,i)=>(t>>>0)+(e>>>0)+(i>>>0),ut=(t,e,i,r)=>e+i+r+(t/2**32|0)|0,lt=(t,e,i,r)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),ft=(t,e,i,r,s)=>e+i+r+s+(t/2**32|0)|0,pt=(t,e,i,r,s)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0)+(s>>>0),bt=(t,e,i,r,s,n)=>e+i+r+s+n+(t/2**32|0)|0;class gt extends Z{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,i,r){super(),this.blockLen=t,this.outputLen=e,this.padOffset=i,this.isLE=r,this.buffer=new Uint8Array(t),this.view=J(this.buffer)}update(t){G(this),W(t=Y(t));const{view:e,buffer:i,blockLen:r}=this,s=t.length;for(let n=0;n<s;){const a=Math.min(r-this.pos,s-n);if(a!==r)i.set(t.subarray(n,n+a),this.pos),this.pos+=a,n+=a,this.pos===r&&(this.process(e,0),this.pos=0);else{const e=J(t);for(;r<=s-n;n+=r)this.process(e,n)}}return this.length+=t.length,this.roundClean(),this}digestInto(t){G(this),function(t,e){W(t);const i=e.outputLen;if(t.length<i)throw new Error(`digestInto() expects output buffer of length at least ${i}`)}(t,this),this.finished=!0;const{buffer:e,view:i,blockLen:r,isLE:s}=this;let{pos:n}=this;e[n++]=128,X(this.buffer.subarray(n)),this.padOffset>r-n&&(this.process(i,0),n=0);for(let t=n;t<r;t++)e[t]=0;!function(t,e,i,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,i,r);const s=BigInt(32),n=BigInt(4294967295),a=Number(i>>s&n),o=Number(i&n),c=r?4:0,h=r?0:4;t.setUint32(e+c,a,r),t.setUint32(e+h,o,r)}(i,r-8,BigInt(8*this.length),s),this.process(i,0);const a=J(t),o=this.outputLen;if(o%4!=0)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t<c;t++)a.setUint32(4*t,h[t],s)}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const i=t.slice(0,e);return this.destroy(),i}_cloneInto(t){t||=new this.constructor,t.set(...this.get());const{blockLen:e,buffer:i,length:r,finished:s,destroyed:n,pos:a}=this;return t.destroyed=n,t.finished=s,t.length=r,t.pos=a,r%e!=0&&t.buffer.set(i),t}clone(){return this._cloneInto()}}const yt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),mt=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),wt=new Uint32Array(64);class It extends gt{A=0|yt[0];B=0|yt[1];C=0|yt[2];D=0|yt[3];E=0|yt[4];F=0|yt[5];G=0|yt[6];H=0|yt[7];constructor(t=32){super(64,t,8,!1)}get(){const{A:t,B:e,C:i,D:r,E:s,F:n,G:a,H:o}=this;return[t,e,i,r,s,n,a,o]}set(t,e,i,r,s,n,a,o){this.A=0|t,this.B=0|e,this.C=0|i,this.D=0|r,this.E=0|s,this.F=0|n,this.G=0|a,this.H=0|o}process(t,e){for(let i=0;i<16;i++,e+=4)wt[i]=t.getUint32(e);for(let t=16;t<64;t++){const e=wt[t-15],r=wt[t-2],s=m(i=e,7)^m(i,18)^i>>>3,n=N(r);wt[t]=I(I(s,wt[t-7]),I(n,wt[t-16]))}var i;let{A:r,B:s,C:n,D:a,E:o,F:c,G:h,H:d}=this;for(let t=0;t<64;t++){const e=S(d,x(o),_(o,c,h),mt[t],wt[t]),i=I(O(r),P(r,s,n));d=h,h=c,c=o,o=I(a,e),a=n,n=s,s=r,r=I(e,i)}this.A=I(this.A,r),this.B=I(this.B,s),this.C=I(this.C,n),this.D=I(this.D,a),this.E=I(this.E,o),this.F=I(this.F,c),this.G=I(this.G,h),this.H=I(this.H,d)}roundClean(){X(wt)}destroy(){X(this.buffer),this.set(0,0,0,0,0,0,0,0)}}const vt=Q((()=>new It)),kt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),St=function(t,e=!1){const i=t.length,r=new Uint32Array(i),s=new Uint32Array(i);for(let n=0;n<i;n++){const{h:i,l:a}=it(t[n],e);r[n]=i,s[n]=a}return[r,s]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((t=>BigInt(t)))),Et=St[0],_t=St[1],Pt=new Uint32Array(80),Ot=new Uint32Array(80);class xt extends gt{Ah=0|kt[0];Al=0|kt[1];Bh=0|kt[2];Bl=0|kt[3];Ch=0|kt[4];Cl=0|kt[5];Dh=0|kt[6];Dl=0|kt[7];Eh=0|kt[8];El=0|kt[9];Fh=0|kt[10];Fl=0|kt[11];Gh=0|kt[12];Gl=0|kt[13];Hh=0|kt[14];Hl=0|kt[15];constructor(t=64){super(128,t,16,!1)}get(){const{Ah:t,Al:e,Bh:i,Bl:r,Ch:s,Cl:n,Dh:a,Dl:o,Eh:c,El:h,Fh:d,Fl:u,Gh:l,Gl:f,Hh:p,Hl:b}=this;return[t,e,i,r,s,n,a,o,c,h,d,u,l,f,p,b]}set(t,e,i,r,s,n,a,o,c,h,d,u,l,f,p,b){this.Ah=0|t,this.Al=0|e,this.Bh=0|i,this.Bl=0|r,this.Ch=0|s,this.Cl=0|n,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|h,this.Fh=0|d,this.Fl=0|u,this.Gh=0|l,this.Gl=0|f,this.Hh=0|p,this.Hl=0|b}process(t,e){for(let i=0;i<16;i++,e+=4)Pt[i]=t.getUint32(e),Ot[i]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|Pt[t-15],i=0|Ot[t-15],r=nt(e,i,1)^nt(e,i,8)^rt(e,0,7),s=at(e,i,1)^at(e,i,8)^st(e,i,7),n=0|Pt[t-2],a=0|Ot[t-2],o=nt(n,a,19)^ot(n,a,61)^rt(n,0,6),c=at(n,a,19)^ct(n,a,61)^st(n,a,6),h=lt(s,c,Ot[t-7],Ot[t-16]),d=ft(h,r,o,Pt[t-7],Pt[t-16]);Pt[t]=0|d,Ot[t]=0|h}let{Ah:i,Al:r,Bh:s,Bl:n,Ch:a,Cl:o,Dh:c,Dl:h,Eh:d,El:u,Fh:l,Fl:f,Gh:p,Gl:b,Hh:g,Hl:y}=this;for(let t=0;t<80;t++){const e=nt(d,u,14)^nt(d,u,18)^ot(d,u,41),m=at(d,u,14)^at(d,u,18)^ct(d,u,41),w=d&l^~d&p,I=pt(y,m,u&f^~u&b,_t[t],Ot[t]),v=bt(I,g,e,w,Et[t],Pt[t]),k=0|I,S=nt(i,r,28)^ot(i,r,34)^ot(i,r,39),E=at(i,r,28)^ct(i,r,34)^ct(i,r,39),_=i&s^i&a^s&a,P=r&n^r&o^n&o;g=0|p,y=0|b,p=0|l,b=0|f,l=0|d,f=0|u,({h:d,l:u}=ht(0|c,0|h,0|v,0|k)),c=0|a,h=0|o,a=0|s,o=0|n,s=0|i,n=0|r;const O=dt(E,P,k);i=ut(O,S,_,v),r=0|O}({h:i,l:r}=ht(i,r,this.Ah,this.Al)),({h:s,l:n}=ht(s,n,this.Bh,this.Bl)),({h:a,l:o}=ht(a,o,this.Ch,this.Cl)),({h:c,l:h}=ht(c,h,this.Dh,this.Dl)),({h:d,l:u}=ht(d,u,this.Eh,this.El)),({h:l,l:f}=ht(l,f,this.Fh,this.Fl)),({h:p,l:b}=ht(p,b,this.Gh,this.Gl)),({h:g,l:y}=ht(g,y,this.Hh,this.Hl)),this.set(i,r,s,n,a,o,c,h,d,u,l,f,p,b,g,y)}roundClean(){X(Pt,Ot)}destroy(){X(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Nt=Q((()=>new xt));class At extends Z{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){super(),function(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash should be wrapped by utils.createHasher");z(t.outputLen),z(t.blockLen)}(t);const i=Y(e);if(this.iHash=t.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,s=new Uint8Array(r);s.set(i.length>r?t.create().update(i).digest():i);for(let t=0;t<s.length;t++)s[t]^=54;this.iHash.update(s),this.oHash=t.create();for(let t=0;t<s.length;t++)s[t]^=106;this.oHash.update(s),X(s)}update(t){return G(this),this.iHash.update(t),this}digestInto(t){G(this),W(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});const{oHash:e,iHash:i,finished:r,destroyed:s,blockLen:n,outputLen:a}=this;return t.finished=r,t.destroyed=s,t.blockLen=n,t.outputLen=a,t.oHash=e._cloneInto(t.oHash??void 0),t.iHash=i._cloneInto(t.iHash??void 0),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Tt=t=>{let e="";for(const r of t)e+=(i=r.toString(16)).length%2==1?"0"+i:i;var i;return e},Ct=(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 Rt(t);case"base64":return Bt(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 s=r;s>65535?i++:s>=55296&&s<=57343&&(s=65533),s<=127?e.push(s):s<=2047?e.push(192|s>>6,128|63&s):s<=65535?e.push(224|s>>12,128|s>>6&63,128|63&s):e.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s)}return e}(t)}},Rt=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},Bt=t=>{const e=[];let i=0,r=0;for(const s of t.replace(/=+$/,""))i=i<<6|"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(s),r+=6,r>=8&&(r-=8,e.push(i>>r&255),i&=(1<<r)-1);return e},Lt=t=>{let e="",i=0;for(let r=0;r<t.length;r++){const s=t[r];if(i>0)i--;else if(s<=127)e+=String.fromCharCode(s);else if(s>=192&&s<=223){i=1;const n=(31&s)<<6|63&t[r+1];e+=String.fromCharCode(n)}else if(s>=224&&s<=239){i=2;const n=(15&s)<<12|(63&t[r+1])<<6|63&t[r+2];e+=String.fromCharCode(n)}else if(s>=240&&s<=247){i=3;const n=(7&s)<<18|(63&t[r+1])<<12|(63&t[r+2])<<6|63&t[r+3],a=55296+(n-65536>>10),o=56320+(n-65536&1023);e+=String.fromCharCode(a,o)}}return e},Mt=(t,e)=>{switch(e){case"hex":return Tt(t);case"utf8":return Lt(t);default:return t}};function Dt(t){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let i,r="";for(i=0;i<t.length;i+=3){const s=t[i],n=i+1<t.length?t[i+1]:0,a=i+2<t.length?t[i+2]:0,o=(3&s)<<4|n>>4,c=(15&n)<<2|a>>6,h=63&a;r+=e.charAt(s>>2)+e.charAt(o),r+=i+1<t.length?e.charAt(c):"=",r+=i+2<t.length?e.charAt(h):"="}return r}const Ft="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Vt=t=>{if(""===t||"string"!=typeof t)throw new Error(`Expected base58 string but got “${t}”`);const e=t.match(/[IOl0]/gmu);if(null!==e)throw new Error(`Invalid base58 character “${e.join("")}”`);const i=t.match(/^1+/gmu),r=null!==i?i[0].length:0,s=(t.length-r)*(Math.log(58)/Math.log(256))+1>>>0,n=new Uint8Array([...new Uint8Array(r),...(t.match(/./gmu)??[]).map((t=>Ft.indexOf(t))).reduce(((t,e)=>t.map((t=>{const i=58*t+e;return e=i>>8,i}))),new Uint8Array(s)).reverse().filter((a=!1,t=>a=a||t))]);var a;return[...n]},Ht=t=>{const e=Array(256).fill(-1);for(let t=0;t<58;++t)e[Ft.charCodeAt(t)]=t;const i=[];for(const r of t){let t=r;for(let r=0;r<i.length;++r){const s=(e[i[r]]<<8)+t;i[r]=Ft.charCodeAt(s%58),t=s/58|0}for(;0!==t;)i.push(Ft.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)},qt=(t,e=[0])=>{let i=K([...e,...t]);return i=[...e,...t,...i.slice(0,4)],Ht(i)},Ut=(t,e,i=1)=>{const r=Vt(t);let s=r.slice(0,i),n=r.slice(i,-4),a=[...s,...n];return a=K(a),r.slice(-4).forEach(((t,e)=>{if(t!==a[e])throw new Error("Invalid checksum")})),"hex"===e&&(s=Tt(s),n=Tt(n)),{prefix:s,data:n}};class Kt{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=Kt.varIntNum(t);return this.write(e),this}writeVarIntBn(t){const e=Kt.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(Wt)),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 Kt;i.writeUInt8(255),i.writeUInt64LEBn(t),e=i.toArray()}return e}}class $t{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(zt)&&(e=e.sub(Wt)),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 jt=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[]},zt=new r(2).pow(new r(63)),Wt=new r(2).pow(new r(64)),Gt=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,Xt=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,Jt=(1n<<256n)-1n;function Yt(t){let e=t>>256n;return e=(t=(t&Jt)+(e<<32n)+977n*e)>>256n,(t=(t&Jt)+(e<<32n)+977n*e)>=Gt&&(t-=Gt),t}const Zt=t=>Yt((t%Gt+Gt)%Gt),Qt=(t,e)=>t>=e?t-e:Gt-(e-t),te=(t,e)=>Yt(t*e),ee=t=>{let e=1n,i=0n,r=Zt(t),s=Gt;for(;r>1n;){const t=s/r;[e,i]=[i-e*t,e],[r,s]=[s-r*t,r]}return Zt(e)},ie=Gt+1n>>2n,re=BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),se=BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),ne=new Map,ae=t=>{const{X:e,Y:i,Z:r}=t;if(0n===i)return{X:0n,Y:1n,Z:0n};const s=te(i,i),n=te(4n,te(e,s)),a=te(3n,te(e,e)),o=Qt(te(a,a),te(2n,n));return{X:o,Y:Qt(te(a,Qt(n,o)),te(8n,te(s,s))),Z:te(2n,te(i,r))}},oe=(t,e)=>{if(0n===t.Z)return e;if(0n===e.Z)return t;const i=te(t.Z,t.Z),r=te(e.Z,e.Z),s=te(t.X,r),n=te(e.X,i),a=te(t.Y,te(r,e.Z)),o=te(e.Y,te(i,t.Z)),c=Qt(n,s),h=Qt(o,a);if(0n===c)return 0n===h?ae(t):{X:0n,Y:1n,Z:0n};const d=te(c,c),u=te(c,d),l=te(s,d),f=Qt(Qt(te(h,h),u),te(2n,l));return{X:f,Y:Qt(te(h,Qt(l,f)),te(a,u)),Z:te(c,te(t.Z,e.Z))}},ce=t=>0n===t.Z?t:{X:t.X,Y:Gt-t.Y,Z:t.Z},he=(t,e,i=5)=>{const r=`${i}:${e.x.toString(16)}:${e.y.toString(16)}`;let s,n=ne.get(r);if(void 0===n){const t=1<<i-1;n=new Array(t),s={X:e.x,Y:e.y,Z:1n},n[0]=s;const a=ae(s);for(let e=1;e<t;e++)n[e]=oe(n[e-1],a);ne.set(r,n)}else s=n[0];const a=[],o=1n<<BigInt(i),c=o>>1n;let h=t;for(;h>0n;)if(0n===(1n&h))a.push(0),h>>=1n;else{let t=h&o-1n;t>c&&(t-=o),a.push(Number(t)),h-=t,h>>=1n}let d={X:0n,Y:1n,Z:0n};for(let t=a.length-1;t>=0;t--){d=ae(d);const e=a[t];if(0!==e){const t=Math.abs(e)>>1,i=e>0?n[t]:ce(n[t]);d=oe(d,i)}}return d},de=t=>{let e=t%Xt;return e<0n&&(e+=Xt),e},ue=(t,e)=>de(t*e),le=t=>{let e=1n,i=0n,r=de(t),s=Xt;for(;r>1n;){const t=s/r;[e,i]=[i-e*t,e],[r,s]=[s-r*t,r]}return de(e)};class fe extends c{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 fe(t.slice(1,33),t.slice(33,65))}if((2===t[0]||3===t[0])&&t.length-1==32)return fe.fromX(t.slice(1,33),3===t[0]);throw new Error("Unknown point format")}static fromString(t){const e=Ct(t,"hex");return fe.fromDER(e)}static fromX(t,e){let i=(t=>r.isBN(t)?BigInt("0x"+t.toString(16)):"string"==typeof t?BigInt("0x"+t):Array.isArray(t)?BigInt("0x"+Tt(t)):BigInt(t))(t);i=Zt(i);var s;const n=(t=>{const e=((t,e)=>{let i=1n;t=Zt(t);let r=e;for(;r>0n;)1n===(1n&r)&&(i=te(i,t)),t=te(t,t),r>>=1n;return i})(t,ie);return te(e,e)===Zt(t)?e:null})((t=>Yt(t+7n))(te(te(s=i,s),i)));if(null===n)throw new Error("Invalid point");let a=n;(1n&a)!==(e?1n:0n)&&(a=Qt(Gt,a));const o=new r(i.toString(16),16),c=new r(a.toString(16),16);return new fe(o,c)}static fromJSON(t,e){"string"==typeof t&&(t=JSON.parse(t));const i=new fe(t[0],t[1],e);if("object"!=typeof t[2])return i;const r=t=>new fe(t[0],t[1],e),s=t[2];return i.precomputed={beta:null,doubles:"object"==typeof s.doubles&&null!==s.doubles?{step:s.doubles.step,points:[i].concat(s.doubles.points.map(r))}:void 0,naf:"object"==typeof s.naf&&null!==s.naf?{wnd:s.naf.wnd,points:[i].concat(s.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 s;return s=t?[this.getY().isEven()?2:3].concat(r):[4].concat(r,this.getY().toArray("be",i)),"hex"!==e?s:Tt(s)}toString(){return this.encode(!0,"hex")}toJSON(){return null==this.precomputed?[this.x,this.y]:[this.x,this.y,"object"==typeof this.precomputed&&null!==this.precomputed?{doubles:null!=this.precomputed.doubles?{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)}:void 0,naf:null!=this.precomputed.naf?{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}:void 0}:void 0]}inspect(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+(this.x?.fromRed()?.toString(16,2)??"undefined")+" y: "+(this.y?.fromRed()?.toString(16,2)??"undefined")+">"}isInfinity(){return this.inf}add(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return new fe(null,null);if(0===this.x?.cmp(t.x??new r(0)))return new fe(null,null);const e={X:BigInt("0x"+this.x.fromRed().toString(16)),Y:BigInt("0x"+this.y.fromRed().toString(16)),Z:1n},i={X:BigInt("0x"+t.x.fromRed().toString(16)),Y:BigInt("0x"+t.y.fromRed().toString(16)),Z:1n},s=oe(e,i);if(0n===s.Z)return new fe(null,null);const n=ee(s.Z),a=te(n,n),o=te(s.X,a),c=te(s.Y,te(a,n));return new fe(o.toString(16),c.toString(16))}dbl(){if(this.inf)return this;if(null===this.x||null===this.y)throw new Error("Point coordinates cannot be null");const t=BigInt("0x"+this.x.fromRed().toString(16)),e=BigInt("0x"+this.y.fromRed().toString(16));if(0n===e)return new fe(null,null);const i=ae({X:t,Y:e,Z:1n}),r=ee(i.Z),s=te(r,r),n=te(i.X,s),a=te(i.Y,te(s,r));return new fe(n.toString(16),a.toString(16))}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)),this.inf)return this;let e=BigInt("0x"+t.toString(16));const i=e<0n;if(i&&(e=-e),e=Zt(e),0n===e)return new fe(null,null);if(null===this.x||null===this.y)throw new Error("Point coordinates cannot be null");let s,n;this===this.curve.g?(s=re,n=se):(s=BigInt("0x"+this.x.fromRed().toString(16)),n=BigInt("0x"+this.y.fromRed().toString(16)));const a=he(e,{x:s,y:n});if(0n===a.Z)return new fe(null,null);const o=ee(a.Z),c=te(o,o),h=te(a.X,c),d=te(a.Y,te(c,o)),u=new r(h.toString(16),16),l=new r(d.toString(16),16),f=new fe(u,l);return i?f.neg():f}mulAdd(t,e,i){const r=[this,e],s=[t,i];return this._endoWnafMulAdd(r,s)}jmulAdd(t,e,i){const r=[this,e],s=[t,i];return this._endoWnafMulAdd(r,s,!0)}eq(t){return this===t||this.inf===t.inf&&(this.inf||0===(this.x??new 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 fe(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 fe((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 fe(t.x.redMul(i.endo.beta),t.y)};t.beta=e,e.precomputed={beta:null,naf:null!=t.naf?{wnd:t.naf.wnd,points:t.naf.points.map(r)}:void 0,doubles:null!=t.doubles?{step:t.doubles.step,points:t.doubles.points.map(r)}:void 0}}return e}_fixedNafMul(t){if("object"!=typeof this.precomputed||null===this.precomputed)throw new Error("_fixedNafMul requires precomputed values for the point");const e=this._getDoubles(),i=this.curve.getNAF(t,1,this.curve._bitLength);let r=(1<<e.step+1)-(e.step%2==0?2:1);r/=3;const s=[];for(let t=0;t<i.length;t+=e.step){let r=0;for(let s=t+e.step-1;s>=t;s--)r=(r<<1)+i[s];s.push(r)}let n=new h(null,null,null),a=new h(null,null,null);for(let t=r;t>0;t--){for(let i=0;i<s.length;i++){const r=s[i];r===t?a=a.mixedAdd(e.points[i]):r===-t&&(a=a.mixedAdd(e.points[i].neg()))}n=n.add(a)}return n.toP()}_wnafMulAdd(t,e,i,s,n){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<s;i++){const r=e[i]._getNAFPoints(t);a[i]=r.wnd,o[i]=r.points}for(let t=s-1;t>=1;t-=2){const s=t-1,n=t;if(1!==a[s]||1!==a[n]){c[s]=this.curve.getNAF(i[s],a[s],this.curve._bitLength),c[n]=this.curve.getNAF(i[n],a[n],this.curve._bitLength),d=Math.max(c[s].length,d),d=Math.max(c[n].length,d);continue}const h=[e[s],null,null,e[n]];0===(e[s].y??new r(0)).cmp(e[n].y??new r(0))?(h[1]=e[s].add(e[n]),h[2]=e[s].toJ().mixedAdd(e[n].neg())):0===(e[s].y??new r(0)).cmp((e[n].y??new r(0)).redNeg())?(h[1]=e[s].toJ().mixedAdd(e[n]),h[2]=e[s].add(e[n].neg())):(h[1]=e[s].toJ().mixedAdd(e[n]),h[2]=e[s].toJ().mixedAdd(e[n].neg()));const u=[-3,-1,-5,-7,0,7,5,1,3],l=this.curve.getJSF(i[s],i[n]);d=Math.max(l[0].length,d),c[s]=new Array(d),c[n]=new Array(d);for(let t=0;t<d;t++){const e=0|l[0][t],i=0|l[1][t];c[s][t]=u[3*(e+1)+(i+1)],c[n][t]=0,o[s]=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<s;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),n=new r(2);for(let t=0;t<s;t++){const e=l[t];let r;0!==e.cmpn(0)&&(r=e.isNeg()?o[t][e.neg().sub(i).div(n).toNumber()].neg():o[t][e.sub(i).div(n).toNumber()],u="affine"===r.type?u.mixedAdd(r):u.add(r))}}for(let t=0;t<s;t++)o[t]=[];return!0===n?u:u.toP()}_endoWnafMulAdd(t,e,i){const r=new Array(2*t.length),s=new Array(2*t.length);let n;for(n=0;n<t.length;n++){const i=this.curve._endoSplit(e[n]);let a=t[n],o=a._getBeta()??new fe(null,null);0!==i.k1.negative&&(i.k1.ineg(),a=a.neg(!0)),0!==i.k2.negative&&(i.k2.ineg(),o=o.neg(!0)),r[2*n]=a,r[2*n+1]=o,s[2*n]=i.k1,s[2*n+1]=i.k2}const a=this._wnafMulAdd(1,r,s,2*n,i);for(let t=0;t<2*n;t++)r[t]=null,s[t]=null;return a}_hasDoubles(t){if(null==this.precomputed)return!1;const e=this.precomputed.doubles;return"object"==typeof e&&e.points.length>=Math.ceil((t.bitLength()+1)/e.step)}_getDoubles(t,e){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.doubles&&null!==this.precomputed.doubles)return this.precomputed.doubles;const i=[this];let r=this;for(let s=0;s<(e??0);s+=t??1){for(let e=0;e<(t??1);e++)r=r.dbl();i.push(r)}return{step:t??1,points:i}}_getNAFPoints(t){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.naf&&null!==this.precomputed.naf)return this.precomputed.naf;const e=[this],i=(1<<t)-1,r=1===i?null:this.dbl();for(let t=1;t<i;t++)null!==r&&(e[t]=e[t-1].add(r));return{wnd:t,points:e}}}let pe;class be{p;red;redN;zero;one;two;g;n;a;b;tinv;zeroA;threeA;endo;_endoWnafT1;_endoWnafT2;_wnafT1;_wnafT2;_wnafT3;_wnafT4;_bitLength;static assert(t,e="Elliptic curve assertion failed"){if(!t)throw new Error(e)}getNAF(t,e,i){const r=new Array(Math.max(t.bitLength(),i)+1);r.fill(0);const s=1<<e+1,n=t.clone();for(let t=0;t<r.length;t++){let e;const i=n.andln(s-1);n.isOdd()?(e=i>(s>>1)-1?(s>>1)-i:i,n.isubn(e)):e=0,r[t]=e,n.iushrn(1)}return r}getJSF(t,e){const i=[[],[]];t=t.clone(),e=e.clone();let r=0,s=0;for(;t.cmpn(-r)>0||e.cmpn(-s)>0;){let n,a,o=t.andln(3)+r&3,c=e.andln(3)+s&3;if(3===o&&(o=-1),3===c&&(c=-1),1&o){const e=t.andln(7)+r&7;n=3!==e&&5!==e||2!==c?o:-o}else n=0;if(i[0].push(n),1&c){const t=e.andln(7)+s&7;a=3!==t&&5!==t||2!==o?c:-c}else a=0;i[1].push(a),2*r===n+1&&(r=1-r),2*s===a+1&&(s=1-s),t.iushrn(1),e.iushrn(1)}return i}static cachedProperty(t,e,i){const r="_"+e;t.prototype[e]=function(){return void 0!==this[r]?this[r]:this[r]=i.call(this)}}static parseBytes(t){return"string"==typeof t?Ct(t,"hex"):t}static intFromLE(t){return new r(t,"hex","le")}constructor(){if(void 0!==pe)return pe;pe=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=fe.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,s;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,s=null!=this.g.x?this.g.x.redMul(e):void 0;if(null!=r&&null!=s&&0===r.cmp(s))i=t[0];else{if(i=t[1],null==this.g)throw new Error("Curve generator point (g) is not defined.");const r=this.g.mul(i)?.x,s=null!=this.g.x?this.g.x.redMul(e):void 0;if(null==r||null==s)throw new Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");be.assert(0===r.cmp(s),"Lambda selection does not match computed beta.")}}return s="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:s}}_getEndoRoots(t){const e=t===this.p?this.red:new o(t),i=new r(2).toRed(e).redInvm(),s=i.redNeg(),n=new r(3).toRed(e).redNeg().redSqrt().redMul(i);return[s.redAdd(n).fromRed(),s.redSub(n).fromRed()]}_getEndoBasis(t){const e=this.n.ushrn(Math.floor(this.n.bitLength()/2));let i,s,n,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===n&&y.cmp(e)<0)i=b.neg(),s=u,n=y.neg(),a=m;else if(void 0!==n&&2==++g)break;b=y,d=h,h=y,f=u,u=m,p=l,l=r}if(void 0===i||void 0===s||void 0===n||void 0===a)throw new Error("Failed to compute Endo Basis values");o=y.neg(),c=m;const w=n.sqr().add(a.sqr());return o.sqr().add(c.sqr()).cmp(w)>=0&&(o=i,c=s),0!==n.negative&&(n=n.neg(),a=a.neg()),0!==o.negative&&(o=o.neg(),c=c.neg()),[{a:n,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],s=r.b.mul(t).divRound(this.n),n=i.b.neg().mul(t).divRound(this.n),a=s.mul(i.a),o=n.mul(r.a),c=s.mul(i.b),h=n.mul(r.b);return{k1:t.sub(a).sub(o),k2:c.add(h).neg()}}validate(t){if(t.inf)return!0;const e=t.x,i=t.y;if(null===e||null===i)throw new Error("Point coordinates cannot be null");const r=this.a.redMul(e),s=e.redSqr().redMul(e).redIAdd(r).redIAdd(this.b);return 0===i.redSqr().redISub(s).cmpn(0)}}class ge{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=Ct(t,e);const s=new class{place;constructor(){this.place=0}};if(48!==t[s.place++])throw new Error("Signature DER must start with 0x30");if(i(t,s)+s.place!==t.length)throw new Error("Signature DER invalid");if(2!==t[s.place++])throw new Error("Signature DER invalid");const n=i(t,s);let a=t.slice(s.place,n+s.place);if(s.place+=n,2!==t[s.place++])throw new Error("Signature DER invalid");const o=i(t,s);if(t.length!==o+s.place)throw new Error("Invalid R-length in signature DER");let c=t.slice(s.place,o+s.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 ge(new r(a),new r(c))}static fromCompact(t,e){if(65!==(t=Ct(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 ge(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 s=new r(U(t,i),16);return Ee(s,this,e)}toString(t){return this.toDER(t)}toDER(t){const e=(t,e)=>{if(!(e<128))throw new Error("len must be < 0x80");t.push(e)},i=t=>{let e=0;const i=t.length-1;for(;0===t[e]&&!(128&t[e+1])&&e<i;)e++;return 0===e?t:t.slice(e)};let r=this.r.toArray(),s=this.s.toArray();for(128&r[0]&&(r=[0].concat(r)),128&s[0]&&(s=[0].concat(s)),r=i(r),s=i(s);0===s[0]&&!(128&s[1]);)s=s.slice(1);let n=[2];e(n,r.length),n=n.concat(r),n.push(2),e(n,s.length);const a=n.concat(s);let o=[48];return e(o,a.length),o=o.concat(a),"hex"===t?Tt(o):"base64"===t?Dt(o):o}toCompact(t,e,i){if(t<0||t>3)throw new Error("Invalid recovery param");if("boolean"!=typeof e)throw new Error("Invalid compressed param");let r=27+t;e&&(r+=4);let s=[r];return s=s.concat(this.r.toArray("be",32)),s=s.concat(this.s.toArray("be",32)),"hex"===i?Tt(s):"base64"===i?Dt(s):s}RecoverPublicKey(t,e){const i=this.r,r=this.s,s=!!(1&t),n=t>>1,a=new be,o=a.n,c=a.g,h=0!==n?i.add(o):i,d=fe.fromX(h,s);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 _e(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 ye{K;V;constructor(t,e){if(t=Ct(t,"hex"),e=Ct(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 H(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(),Tt(i)}}function me(t,e,i=new be){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 we=new be,Ie=we.n.byteLength(),ve=we.n.subn(1),ke=Xt>>1n,Se=(t,e,i=!1,s)=>{t=me(t);const n=BigInt("0x"+t.toString(16)),a=BigInt("0x"+e.toString(16)),o=e.toArray("be",Ie),c=t.toArray("be",Ie),h=new ye(o,c);for(let t=0;;t++){let e="function"==typeof s?s(t):r.isBN(s)?s:new r(h.generate(Ie),16);if(null==e)throw new Error("k is undefined");if(e=me(e,!0),e.cmpn(1)<=0||e.cmp(ve)>=0){if(r.isBN(s))throw new Error("Invalid fixed custom K value (must be >1 and <N‑1)");continue}const o=BigInt("0x"+e.toString(16)),c=he(o,{x:re,y:se});if(0n===c.Z){if(r.isBN(s))throw new Error("Invalid fixed custom K value (k·G at infinity)");continue}const d=ee(c.Z),u=te(d,d),l=te(c.X,u),f=de(l);if(0n===f){if(r.isBN(s))throw new Error("Invalid fixed custom K value (r == 0)");continue}const p=le(o),b=ue(f,a),g=de(n+b);let y=ue(p,g);if(0n===y){if(r.isBN(s))throw new Error("Invalid fixed custom K value (s == 0)");continue}i&&y>ke&&(y=Xt-y);const m=new r(f.toString(16),16),w=new r(y.toString(16),16);return new ge(m,w)}},Ee=(t,e,i)=>{const r=BigInt("0x"+t.toString(16));if(null==i.x||null==i.y)throw new Error("Invalid public key: missing coordinates.");const s={x:BigInt("0x"+i.x.toString(16)),y:BigInt("0x"+i.y.toString(16))},n={r:BigInt("0x"+e.r.toString(16)),s:BigInt("0x"+e.s.toString(16))},{r:a,s:o}=n,c=r;if(a<=0n||a>=Xt||o<=0n||o>=Xt)return!1;const h=le(o);if(0n===h)return!1;const d=ue(c,h),u=ue(a,h),l=he(d,{x:re,y:se}),f=he(u,s),p=oe(l,f);if(0n===p.Z)return!1;const b=ee(p.Z),g=te(b,b),y=te(p.X,g);return de(y)===a};class _e extends fe{static fromPrivateKey(t){const e=(new be).g.mul(t);return new _e(e.x,e.y)}static fromString(t){const e=fe.fromString(t);return new _e(e.x,e.y)}static fromDER(t){const e=fe.fromDER(t);return new _e(e.x,e.y)}constructor(t,e=null,i=!0){if(t instanceof fe)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 s=new r(U(t,i),16);return Ee(s,e,this)}toDER(t){return"hex"===t?this.encode(!0,t):this.encode(!0)}toHash(t){const e=$(this.encode(!0));return"hex"===t?Tt(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 qt(this.toHash(),t)}deriveChild(t,e,i,s){let n;if("function"==typeof s){const e=s(t,this);void 0!==e?n=e:(n=this.deriveSharedSecret(t),"function"==typeof i&&i(t,this,n))}else n=this.deriveSharedSecret(t);const a=Ct(e,"utf8"),o=j(n.encode(!0),a),c=(new be).g.mul(new r(o)),h=this.add(c);return new _e(h.x,h.y)}static fromMsgHashAndCompactSignature(t,e,i){const s=Ct(e,i);if(65!==s.length)throw new Error("Invalid Compact Signature");const n=s[0];if(n<27||n>=35)throw new Error("Invalid Compact Byte");let a=s[0]-27;return a>3&&(a-=4),new ge(new r(s.slice(1,33)),new r(s.slice(33,65))).RecoverPublicKey(a,t)}}class Pe{_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 Oe=null;const xe=t=>(null==Oe&&(Oe=new Pe),Oe.generate(t));class Ne{x;y;constructor(t,e){const i=(new be).p;this.x=t.umod(i),this.y=e.umod(i)}toString(){return Ht(this.x.toArray())+"."+Ht(this.y.toArray())}static fromString(t){const[e,i]=t.split(".");return new Ne(new r(Vt(e)),new r(Vt(i)))}}class Ae{points;threshold;constructor(t,e){this.points=t,this.threshold=e??t.length}static fromPrivateKey(t,e){const i=(new be).p,s=[new Ne(new r(0),new r(t.toArray()))];for(let t=1;t<e;t++){const t=new r(xe(32)).umod(i),e=new r(xe(32)).umod(i);s.push(new Ne(t,e))}return new Ae(s)}valueAt(t){const e=(new be).p;let i=new r(0);for(let r=0;r<this.threshold;r++){let s=this.points[r].y;for(let i=0;i<this.threshold;i++)if(r!==i){const n=this.points[i].x,a=this.points[r].x,o=t.sub(n).umod(e),c=a.sub(n).umod(e).invm(e),h=o.mul(c).umod(e);s=s.mul(h).umod(e)}i=i.add(s).umod(e)}return i}}class Te{points;threshold;integrity;constructor(t,e,i){this.points=t,this.threshold=e,this.integrity=i}static fromBackupFormat(t){let e=0,i="";const r=t.map(((t,r)=>{const s=t.split(".");if(4!==s.length)throw new Error("Invalid share format in share "+r.toString()+'. Expected format: "x.y.t.i" - received '+t);const[n,a,o,c]=s;if(void 0===o)throw new Error("Threshold not found in share "+r.toString());if(void 0===c)throw new Error("Integrity not found in share "+r.toString());const h=parseInt(o);if(0!==r&&e!==h)throw new Error("Threshold mismatch in share "+r.toString());if(0!==r&&i!==c)throw new Error("Integrity mismatch in share "+r.toString());return e=h,i=c,Ne.fromString([n,a].join("."))}));return new Te(r,e,i)}toBackupFormat(){return this.points.map((t=>t.toString()+"."+this.threshold.toString()+"."+this.integrity))}}class Ce extends r{static fromRandom(){return new Ce(xe(32))}static fromString(t,e="hex"){return new Ce(super.fromString(t,e).toArray())}static fromHex(t){return new Ce(super.fromHex(t,"big"))}static fromWif(t,e=1){const i=Ut(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 Ce(i.data.slice(0,32))}constructor(t=0,e=10,i="be",s="apply"){if(t instanceof r?(super(),t.copy(this)):super(t,e,i),"nocheck"!==s){const t=this.checkInField();if(!t.inField){if("error"===s)throw new Error("Input is out of field");r.move(this,t.modN)}}}checkInField(){const t=new be,e=this.mod(t.n);return{inField:0===this.cmp(e),modN:e}}isValid(){return this.checkInField().inField}sign(t,e,i=!0,s){const n=new r(U(t,e),16);return Se(n,this,i,s)}verify(t,e,i){const s=new r(U(t,i),16);return Ee(s,e,this.toPublicKey())}toPublicKey(){const t=(new be).g.mul(this);return new _e(t.x,t.y)}toWif(t=[128]){if(!this.isValid())throw new Error("Value is out of field");return qt([...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,s){let n;if("function"==typeof s){const e=s(this,t);void 0!==e?n=e:(n=this.deriveSharedSecret(t),"function"==typeof i&&i(this,t,n))}else n=this.deriveSharedSecret(t);const a=Ct(e,"utf8"),o=j(n.encode(!0),a),c=new be;return new Ce(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=Ae.fromPrivateKey(this,t),s=[],n=new Set,a=new be,o=xe(64);for(let t=0;t<e;t++){let e,h=0;do{const i=(c=[t,h,...xe(32)],new q(o).update(c,undefined).digest());if(e=new r(i).umod(a.p),h++,h>5)throw new Error("Failed to generate unique x coordinate after 5 attempts")}while(e.isZero()||n.has(e.toString()));n.add(e.toString());const d=i.valueAt(e);s.push(new Ne(e,d))}var c;const h=this.toPublicKey().toHash("hex").slice(0,8);return new Te(s,t,h)}toBackupShares(t,e){return this.toKeyShares(t,e).toBackupFormat()}static fromBackupShares(t){return Ce.fromKeyShares(Te.fromBackupFormat(t))}static fromKeyShares(t){const{points:e,threshold:i,integrity:s}=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 n=new Ae(e,i),a=new Ce(n.valueAt(new r(0)).toArray());if(a.toPublicKey().toHash("hex").slice(0,8)!==s)throw new Error("Integrity hash mismatch");return a}}const Re=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]),Be=[[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))),Le=new Uint8Array(256),Me=new Uint8Array(256);for(let t=0;t<256;t++){const e=255&(t<<1^(128&t?27:0));Le[t]=e,Me[t]=e^t}function De(t,e,i){for(let r=0;r<4;r++){const s=e[i+r];for(let e=0;e<4;e++)t[e][r]^=s[e]}}function Fe(t){for(let e=0;e<4;e++)for(let i=0;i<4;i++)t[e][i]=Re[t[e][i]]}function Ve(t){for(let e=0;e<4;e++)t[e]=Re[t[e]]}function He(t){const e=t[0];t[0]=t[1],t[1]=t[2],t[2]=t[3],t[3]=e}function qe(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 Ue(t){for(let e=0;e<4;e++){const i=t[0][e],r=t[1][e],s=t[2][e],n=t[3][e];t[0][e]=Le[i]^Me[r]^s^n,t[1][e]=i^Le[r]^Me[s]^n,t[2][e]=i^r^Le[s]^Me[n],t[3][e]=Me[i]^r^s^Le[n]}}function Ke(t,e){let i,r,s,n;const a=[[],[],[],[]],o=[],c=Array.from(e);if(c.length<=16){for(;c.length<16;)c.unshift(0);n=11}else if(c.length<=24){for(;c.length<24;)c.unshift(0);n=13}else{if(!(e.length<=32))throw new Error("Illegal key length: "+String(e.length));for(;c.length<32;)c.unshift(0);n=15}const h=function(t,e){const i=e.length/4,r=[];for(let t=0;t<e.length;t++)t%4==0&&r.push([]),r[t>>2].push(e[t]);for(let e=i;e<4*t;e++){r[e]=[];const t=r[e-1].slice();if(e%i==0){He(t),Ve(t);const r=Be[e/i];for(let e=0;e<4;e++)t[e]^=r[e]}else i>6&&e%i==4&&Ve(t);for(let s=0;s<4;s++)r[e][s]=r[e-i][s]^t[s]}return r}(n,c);for(let e=0;e<4;e++)a[0][e]=t[4*e],a[1][e]=t[4*e+1],a[2][e]=t[4*e+2],a[3][e]=t[4*e+3];for(De(a,h,0),s=1;s<n;s++)Fe(a),qe(a),s+1<n&&Ue(a),De(a,h,4*s);for(i=0;i<4;i++)for(r=0;r<4;r++)o.push(a[r][i]);return o}const $e=function(t){return[(4278190080&t)>>>24,(16711680&t)>>16,(65280&t)>>8,255&t]},je=function(t){return new Array(t).fill(0)},ze=[225].concat(je(15)),We=function(t,e){for(let i=0;i<t.length;i++)t[i]^=e[i]},Ge=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},Xe=function(t,e){const i=e.slice(),r=je(16);for(let e=0;e<16;e++)for(let s=7;s>=0;s--)t[e]&1<<s&&We(r,i),1&i[15]?(Ge(i),We(i,ze)):Ge(i);return r},Je=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 Ye(t,e){let i=je(16);for(let r=0;r<t.length;r+=16){const s=i.slice();for(let e=0;e<16;e++)s[e]^=t[r+e]??0;i=Xe(s,e)}return i}function Ze(t,e,i){if(0===t.length)return[];const r=new Array(t.length);let s=e,n=0;const a=Math.ceil(t.length/16);for(let e=0;e<a;e++){const o=Ke(s,i),c=Math.min(16,t.length-n);for(let e=0;e<c;e++)r[n]=t[n]^o[e],n++;e+1<a&&(s=Je(s))}return r}class Qe extends r{static fromRandom(){return new Qe(xe(32))}encrypt(t,e){const i=xe(32);t=Ct(t,e);const{result:r,authenticationTag:s}=function(t,e,i,r){let s,n;const a=Ke(je(16),r);s=[...i],12===i.length?s=s.concat(je(3)).concat([1]):(i.length%16!=0&&(s=s.concat(je(16-i.length%16))),s=s.concat(je(8)),s=Ye(s.concat(je(4)).concat($e(8*i.length)),a));const o=Ze(t,Je(s),r);return n=e.slice(),0===e.length?n=n.concat(je(16)):e.length%16!=0&&(n=n.concat(je(16-e.length%16))),n=n.concat(o),0===o.length?n=n.concat(je(16)):o.length%16!=0&&(n=n.concat(je(16-o.length%16))),n=n.concat(je(4)).concat($e(8*e.length)).concat(je(4)).concat($e(8*o.length)),{result:o,authenticationTag:Ze(Ye(n,a),s,r)}}(t,[],i,this.toArray("be",32));return Mt([...i,...r,...s],e)}decrypt(t,e){const i=(t=Ct(t,e)).slice(0,32),r=t.slice(32),s=r.slice(-16),n=function(t,e,i,r,s){let n,a;const o=Ke(je(16),s);n=[...i],12===i.length?n=n.concat(je(3)).concat([1]):(i.length%16!=0&&(n=n.concat(je(16-i.length%16))),n=n.concat(je(8)),n=Ye(n.concat(je(4)).concat($e(8*i.length)),o));const c=Ze(t,Je(n),s);return a=e.slice(),0===e.length?a=a.concat(je(16)):e.length%16!=0&&(a=a.concat(je(16-e.length%16))),a=a.concat(t),0===t.length?a=a.concat(je(16)):t.length%16!=0&&(a=a.concat(je(16-t.length%16))),a=a.concat(je(4)).concat($e(8*e.length)).concat(je(4)).concat($e(8*t.length)),Ze(Ye(a,o),n,s).join()!==r.join()?null:c}(r.slice(0,-16),[],i,s,this.toArray());if(null===n)throw new Error("Decryption failed!");return Mt(n,e)}}class ti extends ge{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 Kt;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 s=r.satoshis??0;i.writeUInt64LE(s);const n=r.lockingScript?.toBinary()??[];i.writeVarIntNum(n.length),i.write(n)}const r=i.toArray();return K(r)}i.splice(t.inputIndex,0,e);let s=new Array(32).fill(0),n=new Array(32).fill(0),a=new Array(32).fill(0);t.scope&ti.SIGHASH_ANYONECANPAY||(s=(()=>{const t=new Kt;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(Ct(e.sourceTXID,"hex"));t.writeUInt32LE(e.sourceOutputIndex)}const e=t.toArray();return K(e)})()),t.scope&ti.SIGHASH_ANYONECANPAY||(31&t.scope)===ti.SIGHASH_SINGLE||(31&t.scope)===ti.SIGHASH_NONE||(n=(()=>{const t=new Kt;for(const e of i){const i=e.sequence??4294967295;t.writeUInt32LE(i)}const e=t.toArray();return K(e)})()),(31&t.scope)!==ti.SIGHASH_SINGLE&&(31&t.scope)!==ti.SIGHASH_NONE?a=r():(31&t.scope)===ti.SIGHASH_SINGLE&&t.inputIndex<t.outputs.length&&(a=r(t.inputIndex));const o=new Kt;o.writeInt32LE(t.transactionVersion),o.write(s),o.write(n),o.writeReverse(Ct(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 ti(t,e,1)}const e=t[t.length-1],i=t.slice(0,t.length-1),s=ge.fromDER(i);return new ti(s.r,s.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 ei{curve;constructor(){this.curve=new be}generateProof(t,e,i,r){const s=Ce.fromRandom(),n=s.toPublicKey(),a=i.mul(s),o=this.computeChallenge(e,i,r,a,n);return{R:n,SPrime:a,z:s.add(o.mul(t)).umod(this.curve.n)}}verifyProof(t,e,i,r){const{R:s,SPrime:n,z:a}=r,o=this.computeChallenge(t,e,i,n,s),c=this.curve.g.mul(a),h=s.add(t.mul(o));if(!c.eq(h))return!1;const d=e.mul(a),u=n.add(i.mul(o));return!!d.eq(u)}computeChallenge(t,e,i,s,n){const a=[...t.encode(!0),...e.encode(!0),...i.encode(!0),...s.encode(!0),...n.encode(!0)],o=U(a);return new r(o).umod(this.curve.n)}}const ii={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 ii)ii[ii[t]]=t;const ri=ii;class si{chunks;static fromASM(t){const e=[],i=t.split(" ");let r=0;for(;r<i.length;){const t=i[r];let s,n=0;if(t.startsWith("OP_")&&void 0!==ri[t]&&(s=t,n=ri[t]),"0"===t)n=0,e.push({op:n}),r+=1;else if("-1"===t)n=ri.OP_1NEGATE,e.push({op:n}),r+=1;else if(void 0===s){let t=i[r];t.length%2!=0&&(t="0"+t);const s=Ct(t,"hex");if(Mt(s,"hex")!==t)throw new Error("invalid hex string in script");const a=s.length;a>=0&&a<ri.OP_PUSHDATA1?n=a:a<Math.pow(2,8)?n=ri.OP_PUSHDATA1:a<Math.pow(2,16)?n=ri.OP_PUSHDATA2:a<Math.pow(2,32)&&(n=ri.OP_PUSHDATA4),e.push({data:s,op:n}),r+=1}else n===ri.OP_PUSHDATA1||n===ri.OP_PUSHDATA2||n===ri.OP_PUSHDATA4?(e.push({data:Ct(i[r+2],"hex"),op:n}),r+=3):(e.push({op:n}),r+=1)}return new si(e)}static fromHex(t){if(0===t.length)return si.fromBinary([]);if(t.length%2!=0)throw new Error("There is an uneven number of characters in the string which suggests it is not hex encoded.");if(!/^[0-9a-fA-F]+$/.test(t))throw new Error("Some elements in this string are not hex encoded.");return si.fromBinary(Ct(t,"hex"))}static fromBinary(t){t=[...t];const e=[];let i=0;const r=new $t(t);for(;!r.eof();){const t=r.readUInt8();if(t===ri.OP_RETURN&&0===i){e.push({op:t,data:r.read()});break}t===ri.OP_IF||t===ri.OP_NOTIF||t===ri.OP_VERIF||t===ri.OP_VERNOTIF?i++:t===ri.OP_ENDIF&&i--;let s=0,n=[];if(t>0&&t<ri.OP_PUSHDATA1)s=t,e.push({data:r.read(s),op:t});else if(t===ri.OP_PUSHDATA1){try{s=r.readUInt8(),n=r.read(s)}catch{r.read()}e.push({data:n,op:t})}else if(t===ri.OP_PUSHDATA2){try{s=r.readUInt16LE(),n=r.read(s)}catch{r.read()}e.push({data:n,op:t})}else if(t===ri.OP_PUSHDATA4){try{s=r.readUInt32LE(),n=r.read(s)}catch{r.read()}e.push({data:n,op:t})}else e.push({op:t})}return new si(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 Mt(this.toBinary(),"hex")}toBinary(){const t=new Kt;for(let e=0;e<this.chunks.length;e++){const i=this.chunks[e],r=i.op;if(t.writeUInt8(r),r===ri.OP_RETURN&&null!=i.data){t.write(i.data);break}null!=i.data&&(r<ri.OP_PUSHDATA1?t.write(i.data):r===ri.OP_PUSHDATA1?(t.writeUInt8(i.data.length),t.write(i.data)):r===ri.OP_PUSHDATA2?(t.writeUInt16LE(i.data.length),t.write(i.data)):r===ri.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)===ri.OP_0)this.chunks.push({op:ri.OP_0});else if(0===t.cmpn(-1))this.chunks.push({op:ri.OP_1NEGATE});else if(t.cmpn(1)>=0&&t.cmpn(16)<=0)this.chunks.push({op:t.toNumber()+ri.OP_1-1});else{const e=t.toSm("little");this.writeBin(e)}return this}writeBin(t){let e;const i=t.length>0?t:void 0;if(t.length>0&&t.length<ri.OP_PUSHDATA1)e=t.length;else if(0===t.length)e=ri.OP_0;else if(t.length<Math.pow(2,8))e=ri.OP_PUSHDATA1;else if(t.length<Math.pow(2,16))e=ri.OP_PUSHDATA2;else{if(!(t.length<Math.pow(2,32)))throw new Error("You can't push that much data");e=ri.OP_PUSHDATA4}return this.chunks.push({data:i,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!==ri.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 si([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>ri.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} ${ri[e]}`:`${i} ${Tt(t.data)}`,i}}class ni extends si{isLockingScript(){return!0}isUnlockingScript(){return!1}}class ai extends si{isLockingScript(){return!1}isUnlockingScript(){return!0}}class oi extends Error{txid;outputIndex;context;programCounter;stackState;altStackState;ifStackState;stackMem;altStackMem;constructor(t){const e=t.stackState.map((t=>null!=t&&void 0!==t.length?Tt(t):null==t?"null/undef":"INVALID_STACK_ITEM")).join(", "),i=t.altStackState.map((t=>null!=t&&void 0!==t.length?Tt(t):null==t?"null/undef":"INVALID_STACK_ITEM")).join(", "),r=`Context: ${t.context}, PC: ${t.programCounter}`,s=`Stack: [${e}] (len: ${t.stackState.length}, mem: ${t.stackMem})`,n=`AltStack: [${i}] (len: ${t.altStackState.length}, mem: ${t.altStackMem})`,a=`IfStack: [${t.ifStackState.join(", ")}]`;super(`Script evaluation error: ${t.message}\nTXID: ${t.txid}, OutputIdx: ${t.outputIndex}\n${r}\n${s}\n${n}\n${a}`),this.name=this.constructor.name,this.txid=t.txid,this.outputIndex=t.outputIndex,this.context=t.context,this.programCounter=t.programCounter,this.stackState=t.stackState.map((t=>t.slice())),this.altStackState=t.altStackState.map((t=>t.slice())),this.ifStackState=t.ifStackState.slice(),this.stackMem=t.stackMem,this.altStackMem=t.altStackMem}}const ci=1073741824,hi=Math.pow(2,31)-1,di=!0,ui=Object.freeze(new r(-1).toScriptNum()),li=Object.freeze(Array.from({length:17},((t,e)=>Object.freeze(new r(e).toScriptNum()))));class fi{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,s=t[r],n=t[r+1];if(2!==s)return!1;if(0===n)return!1;if(128&t[4])return!1;if(i>1&&0===t[4]&&!(128&t[5]))return!1;const a=r+2;return!(128&t[a]||n>1&&0===t[a]&&!(128&t[a+1])||i+n+7!==t.length)}(t))return this.scriptEvaluationError("The signature format is invalid."),!1;try{const e=ti.fromChecksigFormat(t);if(!e.hasLowS())return this.scriptEvaluationError("The signature must have a low S value."),!1;if(!(e.scope&ti.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{_e.fromDER(t)}catch(t){return this.scriptEvaluationError("The public key is in an unknown format."),!1}return!0}verifySignature(t,e,i){const s=ti.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}),n=new r(K(s));return Ee(n,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>ci&&this.scriptEvaluationError(`Data push > 1073741824 bytes (pc=${this.programCounter}).`);const s=!this.ifStack.includes(!1);var n,a;if(s&&((n=i)===ri.OP_2MUL||n===ri.OP_2DIV||n===ri.OP_VERIF||n===ri.OP_VERNOTIF||n===ri.OP_VER)&&this.scriptEvaluationError(`This opcode is currently disabled. (Opcode: ${ri[i]}, PC: ${this.programCounter})`),s&&i>=0&&i<=ri.OP_PUSHDATA4)(function(t){const e=t.data,i=t.op;return!(Array.isArray(e)&&(0===e.length?i!==ri.OP_0:1===e.length&&e[0]>=1&&e[0]<=16?i!==ri.OP_1+(e[0]-1):1===e.length&&129===e[0]?i!==ri.OP_1NEGATE:e.length<=75?i!==e.length:e.length<=255?i!==ri.OP_PUSHDATA1:e.length<=65535&&i!==ri.OP_PUSHDATA2))})(e)||this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`),this.pushStack(Array.isArray(e.data)?e.data:[]);else if(s||i>=ri.OP_IF&&i<=ri.OP_ENDIF){let t,e,n,o,c,h,d,u,l,f,p,b,g,y,m,w,I,v,k,S,E,_,P,O,x,N;switch(i){case ri.OP_1NEGATE:this.pushStackCopy(ui);break;case ri.OP_0:this.pushStackCopy(li[0]);break;case ri.OP_1:case ri.OP_2:case ri.OP_3:case ri.OP_4:case ri.OP_5:case ri.OP_6:case ri.OP_7:case ri.OP_8:case ri.OP_9:case ri.OP_10:case ri.OP_11:case ri.OP_12:case ri.OP_13:case ri.OP_14:case ri.OP_15:case ri.OP_16:b=i-(ri.OP_1-1),this.pushStackCopy(li[b]);break;case ri.OP_NOP:case ri.OP_NOP2:case ri.OP_NOP3:case ri.OP_NOP1:case ri.OP_NOP4:case ri.OP_NOP5:case ri.OP_NOP6:case ri.OP_NOP7:case ri.OP_NOP8:case ri.OP_NOP9:case ri.OP_NOP10:case ri.OP_NOP11:case ri.OP_NOP12:case ri.OP_NOP13:case ri.OP_NOP14:case ri.OP_NOP15:case ri.OP_NOP16:case ri.OP_NOP17:case ri.OP_NOP18:case ri.OP_NOP19:case ri.OP_NOP20:case ri.OP_NOP21:case ri.OP_NOP22:case ri.OP_NOP23:case ri.OP_NOP24:case ri.OP_NOP25:case ri.OP_NOP26:case ri.OP_NOP27:case ri.OP_NOP28:case ri.OP_NOP29:case ri.OP_NOP30:case ri.OP_NOP31:case ri.OP_NOP32:case ri.OP_NOP33:case ri.OP_NOP34:case ri.OP_NOP35:case ri.OP_NOP36:case ri.OP_NOP37:case ri.OP_NOP38:case ri.OP_NOP39:case ri.OP_NOP40:case ri.OP_NOP41:case ri.OP_NOP42:case ri.OP_NOP43:case ri.OP_NOP44:case ri.OP_NOP45:case ri.OP_NOP46:case ri.OP_NOP47:case ri.OP_NOP48:case ri.OP_NOP49:case ri.OP_NOP50:case ri.OP_NOP51:case ri.OP_NOP52:case ri.OP_NOP53:case ri.OP_NOP54:case ri.OP_NOP55:case ri.OP_NOP56:case ri.OP_NOP57:case ri.OP_NOP58:case ri.OP_NOP59:case ri.OP_NOP60:case ri.OP_NOP61:case ri.OP_NOP62:case ri.OP_NOP63:case ri.OP_NOP64:case ri.OP_NOP65:case ri.OP_NOP66:case ri.OP_NOP67:case ri.OP_NOP68:case ri.OP_NOP69:case ri.OP_NOP70:case ri.OP_NOP71:case ri.OP_NOP72:case ri.OP_NOP73:case ri.OP_NOP77:break;case ri.OP_IF:case ri.OP_NOTIF:y=!1,s&&(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===ri.OP_NOTIF&&(y=!y)),this.ifStack.push(y);break;case ri.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 ri.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop();break;case ri.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 ri.OP_RETURN:"UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.ifStack=[],this.programCounter--;break;case ri.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 ri.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 ri.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 ri.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),e=this.stackTop(-2),n=this.stackTop(-1),this.pushStackCopy(e),this.pushStackCopy(n);break;case ri.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),e=this.stackTop(-3),n=this.stackTop(-2),o=this.stackTop(-1),this.pushStackCopy(e),this.pushStackCopy(n),this.pushStackCopy(o);break;case ri.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),e=this.stackTop(-4),n=this.stackTop(-3),this.pushStackCopy(e),this.pushStackCopy(n);break;case ri.OP_2ROT:{this.stack.length<6&&this.scriptEvaluationError("OP_2ROT requires at least six items to be on the stack.");const t=this.popStack(),e=this.popStack(),i=this.popStack(),r=this.popStack(),s=this.popStack(),n=this.popStack();this.pushStack(r),this.pushStack(i),this.pushStack(e),this.pushStack(t),this.pushStack(n),this.pushStack(s);break}case ri.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 ri.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 ri.OP_DEPTH:this.pushStack(new r(this.stack.length).toScriptNum());break;case ri.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),this.popStack();break;case ri.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 ri.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),n=this.popStack(),this.popStack(),this.pushStack(n);break;case ri.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 ri.OP_PICK:case ri.OP_ROLL:{this.stack.length<2&&this.scriptEvaluationError(`${ri[i]} requires at least two items to be on the stack.`),u=r.fromScriptNum(this.popStack(),di),b=u.toNumber(),(b<0||b>=this.stack.length)&&this.scriptEvaluationError(`${ri[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===ri.OP_ROLL?(this.stack.splice(this.stack.length-1-b,1),this.stackMem-=t.length,this.pushStack(t)):this.pushStackCopy(t);break}case ri.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 ri.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 ri.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 ri.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 ri.OP_AND:case ri.OP_OR:case ri.OP_XOR:{this.stack.length<2&&this.scriptEvaluationError(`${ri[i]} requires at least two items on the stack.`),n=this.popStack(),e=this.popStack(),e.length!==n.length&&this.scriptEvaluationError(`${ri[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===ri.OP_AND?t[r]=e[r]&n[r]:i===ri.OP_OR?t[r]=e[r]|n[r]:t[r]=e[r]^n[r];this.pushStack(t);break}case ri.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 ri.OP_LSHIFT:case ri.OP_RSHIFT:{if(this.stack.length<2&&this.scriptEvaluationError(`${ri[i]} requires at least two items to be on the stack.`),f=r.fromScriptNum(this.popStack(),di),e=this.popStack(),b=f.toNumber(),b<0&&this.scriptEvaluationError(`${ri[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===ri.OP_LSHIFT?l.ushln(b):l.ushrn(b);const s=t.toArray("le",e.length);this.pushStack(s);break}case ri.OP_EQUAL:case ri.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${ri[i]} requires at least two items to be on the stack.`),n=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,n),this.pushStack(y?[1]:[]),i===ri.OP_EQUALVERIFY&&(y||this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."),this.popStack());break;case ri.OP_1ADD:case ri.OP_1SUB:case ri.OP_NEGATE:case ri.OP_ABS:case ri.OP_NOT:case ri.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${ri[i]} requires at least one item to be on the stack.`),u=r.fromScriptNum(this.popStack(),di),i){case ri.OP_1ADD:u=u.add(new r(1));break;case ri.OP_1SUB:u=u.sub(new r(1));break;case ri.OP_NEGATE:u=u.neg();break;case ri.OP_ABS:u.isNeg()&&(u=u.neg());break;case ri.OP_NOT:u=new r(0===u.cmpn(0)?1:0);break;case ri.OP_0NOTEQUAL:u=new r(0!==u.cmpn(0)?1:0)}this.pushStack(u.toScriptNum());break;case ri.OP_ADD:case ri.OP_SUB:case ri.OP_MUL:case ri.OP_DIV:case ri.OP_MOD:case ri.OP_BOOLAND:case ri.OP_BOOLOR:case ri.OP_NUMEQUAL:case ri.OP_NUMEQUALVERIFY:case ri.OP_NUMNOTEQUAL:case ri.OP_LESSTHAN:case ri.OP_GREATERTHAN:case ri.OP_LESSTHANOREQUAL:case ri.OP_GREATERTHANOREQUAL:case ri.OP_MIN:case ri.OP_MAX:{this.stack.length<2&&this.scriptEvaluationError(`${ri[i]} requires at least two items to be on the stack.`),n=this.popStack(),e=this.popStack(),f=r.fromScriptNum(n,di),l=r.fromScriptNum(e,di);let t=0;switch(i){case ri.OP_MUL:t=l.byteLength()+f.byteLength();break;case ri.OP_ADD:case ri.OP_SUB:t=Math.max(l.byteLength(),f.byteLength())+1;break;default:t=Math.max(l.byteLength(),f.byteLength())}this.ensureStackMem(t);let s=new r(0);switch(i){case ri.OP_ADD:s=l.add(f);break;case ri.OP_SUB:s=l.sub(f);break;case ri.OP_MUL:s=l.mul(f);break;case ri.OP_DIV:0===f.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),s=l.div(f);break;case ri.OP_MOD:0===f.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),s=l.mod(f);break;case ri.OP_BOOLAND:s=new r(0!==l.cmpn(0)&&0!==f.cmpn(0)?1:0);break;case ri.OP_BOOLOR:s=new r(0!==l.cmpn(0)||0!==f.cmpn(0)?1:0);break;case ri.OP_NUMEQUAL:case ri.OP_NUMEQUALVERIFY:s=new r(0===l.cmp(f)?1:0);break;case ri.OP_NUMNOTEQUAL:s=new r(0!==l.cmp(f)?1:0);break;case ri.OP_LESSTHAN:s=new r(l.cmp(f)<0?1:0);break;case ri.OP_GREATERTHAN:s=new r(l.cmp(f)>0?1:0);break;case ri.OP_LESSTHANOREQUAL:s=new r(l.cmp(f)<=0?1:0);break;case ri.OP_GREATERTHANOREQUAL:s=new r(l.cmp(f)>=0?1:0);break;case ri.OP_MIN:s=l.cmp(f)<0?l:f;break;case ri.OP_MAX:s=l.cmp(f)>0?l:f}this.pushStack(s.toScriptNum()),i===ri.OP_NUMEQUALVERIFY&&(this.castToBool(this.stackTop())||this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."),this.popStack());break}case ri.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(),di),f=r.fromScriptNum(this.popStack(),di),l=r.fromScriptNum(this.popStack(),di),y=l.cmp(f)>=0&&l.cmp(p)<0,this.pushStack(y?[1]:[]);break;case ri.OP_RIPEMD160:case ri.OP_SHA1:case ri.OP_SHA256:case ri.OP_HASH160:case ri.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${ri[i]} requires at least one item to be on the stack.`),t=this.popStack();let e=[];i===ri.OP_RIPEMD160?(a=t,e=(new D).update(a,undefined).digest()):i===ri.OP_SHA1?e=(t=>(new V).update(t,void 0).digest())(t):i===ri.OP_SHA256?e=U(t):i===ri.OP_HASH160?e=$(t):i===ri.OP_HASH256&&(e=K(t)),this.pushStack(e);break}case ri.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case ri.OP_CHECKSIG:case ri.OP_CHECKSIGVERIFY:{this.stack.length<2&&this.scriptEvaluationError(`${ri[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(`${ri[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 si(t),w.findAndDelete((new si).writeBin(I)),m=!1,I.length>0)try{k=ti.fromChecksigFormat(I),S=_e.fromDER(v),m=this.verifySignature(k,S,w)}catch(t){m=!1}this.pushStack(m?[1]:[]),i===ri.OP_CHECKSIGVERIFY&&(m||this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."),this.popStack());break}case ri.OP_CHECKMULTISIG:case ri.OP_CHECKMULTISIGVERIFY:{E=1,this.stack.length<E&&this.scriptEvaluationError(`${ri[i]} requires at least 1 item for nKeys.`),O=r.fromScriptNum(this.stackTop(-E),di).toNumber(),(O<0||O>hi)&&this.scriptEvaluationError(`${ri[i]} requires a key count between 0 and ${hi}.`),_=++E,E+=O,this.stack.length<E&&this.scriptEvaluationError(`${ri[i]} stack too small for nKeys and keys. Need ${E}, have ${this.stack.length}.`),x=r.fromScriptNum(this.stackTop(-E),di).toNumber(),(x<0||x>O)&&this.scriptEvaluationError(`${ri[i]} requires the number of signatures to be no greater than the number of keys.`),P=++E,E+=x,this.stack.length<E&&this.scriptEvaluationError(`${ri[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 si(t);for(let t=0;t<x;t++)I=this.stackTop(-P-t),w.findAndDelete((new si).writeBin(I));for(m=!0;m&&x>0;){if(0===O){m=!1;break}if(I=this.stackTop(-P),v=this.stackTop(-_),this.checkSignatureEncoding(I)&&this.checkPublicKeyEncoding(v)||this.scriptEvaluationError(`${ri[i]} requires correct encoding for the public key and signature.`),N=!1,I.length>0)try{k=ti.fromChecksigFormat(I),S=_e.fromDER(v),N=this.verifySignature(k,S,w)}catch(t){N=!1}N&&(P++,x--),_++,O--,x>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(`${ri[i]} requires an extra item (dummy) to be on the stack.`),this.popStack().length>0&&this.scriptEvaluationError(`${ri[i]} requires the extra stack item (dummy) to be empty.`),this.pushStack(m?[1]:[]),i===ri.OP_CHECKMULTISIGVERIFY&&(m||this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),this.popStack());break}case ri.OP_CAT:{this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),n=this.popStack(),e=this.popStack();const t=e.concat(n);t.length>ci&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),this.pushStack(t);break}case ri.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,di).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 ri.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(),di).toNumber(),(g>ci||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=jt(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 ri.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=jt(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){throw new oi({message:t,txid:this.sourceTXID,outputIndex:this.sourceOutputIndex,context:this.context,programCounter:this.programCounter,stackState:this.stack,altStackState:this.altStack,ifStackState:this.ifStack,stackMem:this.stackMem,altStackMem:this.altStackMem})}}function pi(t){if(null==t)throw new Error("must have value");return t}class bi{lock(t){let e;if("string"==typeof t){const i=Ut(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 ni([{op:ri.OP_DUP},{op:ri.OP_HASH160},{op:e.length,data:e},{op:ri.OP_EQUALVERIFY},{op:ri.OP_CHECKSIG}])}unlock(t,e="all",i=!1,r,s){return{sign:async(n,a)=>{let o=ti.SIGHASH_FORKID;"all"===e&&(o|=ti.SIGHASH_ALL),"none"===e&&(o|=ti.SIGHASH_NONE),"single"===e&&(o|=ti.SIGHASH_SINGLE),i&&(o|=ti.SIGHASH_ANYONECANPAY);const c=n.inputs[a],h=n.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(s||=c.sourceTransaction?.outputs[c.sourceOutputIndex].lockingScript,null==s)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");const u=ti.format({sourceTXID:d,sourceOutputIndex:pi(c.sourceOutputIndex),sourceSatoshis:r,transactionVersion:n.version,otherInputs:h,inputIndex:a,outputs:n.outputs,inputSequence:pi(c.sequence),subscript:s,lockTime:n.lockTime,scope:o}),l=t.sign(U(u)),f=new ti(l.r,l.s,o).toChecksigFormat(),p=t.toPublicKey().encode(!0);return new ai([{op:f.length,data:f},{op:p.length,data:p}])},estimateLength:async()=>108}}}function gi(t){if(null==t)throw new Error("must have value");return t}class yi{wallet;originator;static decode(t){const e=_e.fromString(Tt(gi(t.chunks[0].data))),i=[];for(let e=2;e<t.chunks.length;e++){const r=t.chunks[e+1]?.op;let s=t.chunks[e].data??[];if(0===s.length&&(t.chunks[e].op>=80&&t.chunks[e].op<=95?s=[t.chunks[e].op-80]:0===t.chunks[e].op?s=[0]:79===t.chunks[e].op&&(s=[129])),i.push(s),r===ri.OP_DROP||r===ri.OP_2DROP)break}return{fields:i,lockingPublicKey:e}}constructor(t,e){this.wallet=t,this.originator=e}async lock(t,e,i,r,s=!1,n=!0,a="before"){const{publicKey:o}=await this.wallet.getPublicKey({protocolID:e,keyID:i,counterparty:r,forSelf:s},this.originator),c=[],h=[];if(c.push({op:o.length/2,data:Ct(o,"hex")}),c.push({op:ri.OP_CHECKSIG}),n){const s=t.reduce(((t,e)=>[...t,...e]),[]),{signature:n}=await this.wallet.createSignature({data:s,protocolID:e,keyID:i,counterparty:r},this.originator);t.push(n)}for(const e of t)h.push(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:ri.OP_2DROP}),u-=2;return 0!==u&&h.push({op:ri.OP_DROP}),new ni("before"===a?[...c,...h]:[...h,...c])}unlock(t,e,i,r="all",s=!1,n,a){return{sign:async(o,c)=>{let h=ti.SIGHASH_FORKID;"all"===r&&(h|=ti.SIGHASH_ALL),"none"===r&&(h|=ti.SIGHASH_NONE),"single"===r&&(h|=ti.SIGHASH_SINGLE),s&&(h|=ti.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(n||=d.sourceTransaction?.outputs[d.sourceOutputIndex].satoshis,null==n||void 0===n)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=ti.format({sourceTXID:l,sourceOutputIndex:gi(d.sourceOutputIndex),sourceSatoshis:n,transactionVersion:o.version,otherInputs:u,inputIndex:c,outputs:o.outputs,inputSequence:d.sequence??4294967295,subscript:a,lockTime:o.lockTime,scope:h}),p=U(f),{signature:b}=await this.wallet.createSignature({data:p,protocolID:t,keyID:e,counterparty:i},this.originator),g=ge.fromDER([...b]),y=new ti(g.r,g.s,h).toChecksigFormat();return new ai([{op:y.length,data:y}])},estimateLength:async()=>73}}}class mi{value;constructor(t){this.value=t}async computeFee(t){const e=t=>t>2**32?9:t>65536?5:t>253?3:1;let i=4;i+=e(t.inputs.length);for(let r=0;r<t.inputs.length;r++){const s=t.inputs[r];let n;if(i+=40,"object"==typeof s.unlockingScript)n=s.unlockingScript.toBinary().length;else{if("object"!=typeof s.unlockingScriptTemplate)throw new Error("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");n=await s.unlockingScriptTemplate.estimateLength(t,r)}i+=e(n),i+=n}i+=e(t.outputs.length);for(const r of t.outputs){i+=8;const t=r.lockingScript.toBinary().length;i+=e(t),i+=t}return i+=4,Math.ceil(i/1e3*this.value)}}class wi extends mi{static ARC_POLICY_URL="https://arc.gorillapool.io/v1/policy";static instance=null;cachedRate=null;cacheTimestamp=0;cacheValidityMs;constructor(t=3e5){super(100),this.cacheValidityMs=t}static getInstance(t=3e5){return wi.instance||(wi.instance=new wi(t)),wi.instance}async fetchFeeRate(){const t=Date.now();if(null!==this.cachedRate&&t-this.cacheTimestamp<this.cacheValidityMs)return this.cachedRate;try{const e=await fetch(wi.ARC_POLICY_URL);if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const i=await e.json();if(!i.policy?.miningFee||"number"!=typeof i.policy.miningFee.satoshis||"number"!=typeof i.policy.miningFee.bytes)throw new Error("Invalid policy response format");const r=i.policy.miningFee.satoshis/i.policy.miningFee.bytes*1e3;return this.cachedRate=r,this.cacheTimestamp=t,r}catch(t){return null!==this.cachedRate?(console.warn("Failed to fetch live fee rate, using cached value:",t),this.cachedRate):(console.warn("Failed to fetch live fee rate, using default 100 sat/kb:",t),100)}}async computeFee(t){const e=await this.fetchFeeRate();return this.value=e,super.computeFee(t)}}class Ii{https;constructor(t){this.https=t}async request(t,e){return await new Promise(((i,r)=>{const s=this.https.request(t,e,(t=>{let e="";t.on("data",(t=>{e+=t})),t.on("end",(()=>{const r=t.statusCode>=200&&t.statusCode<=299,s=t.headers["content-type"],n=""!==e&&"string"==typeof s&&s.startsWith("application/json")?JSON.parse(e):e;i({status:t.statusCode,statusText:t.statusMessage,ok:r,data:n})}))}));s.on("error",(t=>{r(t)})),null!==e.data&&void 0!==e.data&&s.write(JSON.stringify(e.data)),s.end()}))}}class vi{fetch;constructor(t){this.fetch=t}async request(t,e){const i={method:e.method,headers:e.headers,body:JSON.stringify(e.data)},r=await this.fetch(t,i),s=r.headers.get("Content-Type"),n=s?.startsWith("application/json")?await r.json():await r.text();return{ok:r.ok,status:r.status,statusText:r.statusText,data:n}}}function ki(){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 vi(window.fetch.bind(window));if("undefined"==typeof require)return t;try{const t=require("https");return new Ii(t)}catch(e){return t}}function Si(){return`ts-sdk-${Tt(xe(16))}`}class Ei{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(t,e){if(this.URL=t,"string"==typeof e)this.apiKey=e,this.httpClient=ki(),this.deploymentId=Si(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const t=e??{},{apiKey:i,deploymentId:r,httpClient:s,callbackToken:n,callbackUrl:a,headers:o}=t;this.apiKey=i,this.httpClient=s??ki(),this.deploymentId=r??Si(),this.callbackToken=n,this.callbackUrl=a,this.headers=o}}requestHeaders(){const t={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(null!=this.apiKey&&""!==this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),null!=this.callbackUrl&&""!==this.callbackUrl&&(t["X-CallbackUrl"]=this.callbackUrl),null!=this.callbackToken&&""!==this.callbackToken&&(t["X-CallbackToken"]=this.callbackToken),null!=this.headers)for(const e in this.headers)t[e]=this.headers[e];return t}async broadcast(t){let e;try{e=t.toHexEF()}catch(i){if("All inputs must have source transactions when serializing to EF format"!==i.message)throw i;e=t.toHex()}const i={method:"POST",headers:this.requestHeaders(),data:{rawTx:e}};try{const t=await this.httpClient.request(`${this.URL}/v1/tx`,i);if(t.ok){const{txid:e,extraInfo:i,txStatus:r,competingTxs:s}=t.data,n={status:"success",txid:e,message:`${r} ${i}`};return null!=s&&(n.competingTxs=s),n}{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 _i{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??ki(),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 Pi{blockHeight;path;static fromHex(t){return Pi.fromBinary(Ct(t,"hex"))}static fromReader(t,e=!0){const i=t.readVarIntNum(),r=t.readUInt8(),s=Array(r).fill(null).map((()=>[]));let n,a,o;for(let e=0;e<r;e++){for(o=t.readVarIntNum();o>0;){a=t.readVarIntNum(),n=t.readUInt8();const i={offset:a};1&n?i.duplicate=!0:(2&n&&(i.txid=!0),i.hash=Tt(t.read(32).reverse())),Array.isArray(s[e])&&0!==s[e].length||(s[e]=[]),s[e].push(i),o--}s[e].sort(((t,e)=>t.offset-e.offset))}return new Pi(i,s,e)}static fromBinary(t){const e=new $t(t);return Pi.fromReader(e)}static fromCoinbaseTxidAndHeight(t,e){return new Pi(e,[[{offset:0,hash:t,txid:!0}]])}constructor(t,e,i=!0){this.blockHeight=t,this.path=e;const r=Array(this.path.length).fill(0).map((()=>new Set));let s;this.path.forEach(((t,e)=>{if(0===t.length&&0===e)throw new Error(`Empty level at height: ${e}`);const s=new Set;t.forEach((t=>{if(s.has(t.offset))throw new Error(`Duplicate offset: ${t.offset}, at height: ${e}`);if(s.add(t.offset),0===e){if(!0!==t.duplicate)for(let e=1;e<this.path.length;e++)r[e].add(t.offset>>e^1)}else if(i&&!r[e].has(t.offset))throw new Error(`Invalid offset: ${t.offset}, at height: ${e}, with legal offsets: ${Array.from(r[e]).join(", ")}`)}))})),this.path[0].forEach(((t,e)=>{if(0===e&&(s=this.computeRoot(t.hash)),s!==this.computeRoot(t.hash))throw new Error("Mismatched roots")}))}toBinary(){const t=new Kt;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(Ct(e.hash,"hex").reverse())}}return t.toArray()}toHex(){return Tt(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=>Tt(K(Ct(t,"hex").reverse()).reverse());let r=t;if(1===this.path.length&&1===this.path[0].length)return r;for(let t=0;t<this.path.length;t++){this.path[t];const s=e>>t^1,n=this.findOrComputeLeaf(t,s);if("object"!=typeof n)throw new Error(`Missing hash for index ${e} at height ${t}`);r=!0===n.duplicate?i((r??"")+(r??"")):i(s%2!=0?(n.hash??"")+(r??""):(r??"")+(n.hash??""))}return r}findOrComputeLeaf(t,e){const i=t=>Tt(K(Ct(t,"hex").reverse()).reverse());let r=this.path[t].find((t=>t.offset===e));if(null!=r)return r;if(0===t)return;const s=t-1,n=e<<1,a=this.findOrComputeLeaf(s,n);if(null==a||null==a.hash||""===a.hash)return;const o=this.findOrComputeLeaf(s,n+1);if(null==o)return;let c;return c=!0===o.duplicate?i(a.hash+a.hash):i((o.hash??"")+(a.hash??"")),r={offset:e,hash:c},r}async verify(t,e){const i=this.computeRoot(t);if(0===this.indexOf(t)){const t=await e.currentHeight();if(this.blockHeight+100<t)return!1}return await e.isValidRootForHeight(i,this.blockHeight)}combine(t){if(this.blockHeight!==t.blockHeight)throw new Error("You cannot combine paths which do not have the same block height.");if(this.computeRoot()!==t.computeRoot())throw new Error("You cannot combine paths which do not have the same root.");const e=[];for(let i=0;i<this.path.length;i++){e.push([]);for(let t=0;t<this.path[i].length;t++)e[i].push(this.path[i][t]);for(let r=0;r<t.path[i].length;r++)if(void 0===e[i].find((e=>e.offset===t.path[i][r].offset)))e[i].push(t.path[i][r]);else if(void 0!==t.path[i][r]?.txid&&null!==t.path[i][r]?.txid){const s=e[i].find((e=>e.offset===t.path[i][r].offset));null!=s&&(s.txid=!0)}}this.path=e,this.trim()}trim(){const t=(t,e)=>{0!==e.length&&e.slice(-1)[0]===t||e.push(t)},e=(t,e)=>{for(let i=t.length;i>=0;i--){const r=this.path[e].findIndex((e=>e.offset===t[i]));r>=0&&this.path[e].splice(r,1)}},i=e=>{const i=[];for(const r of e)t(r>>1,i);return i};let r=[],s=[];for(let t=0;t<this.path.length;t++)this.path[t].sort(((t,e)=>t.offset-e.offset));for(let e=0;e<this.path[0].length;e++){const i=this.path[0][e];if(!0===i.txid)t(i.offset>>1,r);else{const r=i.offset%2==1,n=this.path[0][e+(r?-1:1)];void 0!==n.txid&&null!==n.txid&&n.txid||t(n.offset,s)}}e(s,0);for(let t=1;t<this.path.length;t++)s=r,r=i(r),e(s,t)}}class Oi{_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=Tt(K(this._rawTx)),this._txid;throw new Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=Li.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 Oi(t,e)}static fromRawTx(t,e){return new Oi(t,e)}static fromTxid(t,e){return new Oi(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===Ai?this.isTxidOnly?(i(Ci.TXID_ONLY),(()=>{if(null==this._txid)throw new Error("Transaction ID (_txid) is undefined");t.writeReverse(Ct(this._txid,"hex"))})()):void 0!==this.bumpIndex?(i(Ci.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex),r()):(i(Ci.RAWTX),r()):(r(),(()=>{void 0===this.bumpIndex?i(Ci.RAWTX):(i(Ci.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex))})())}static fromReader(t,e){let i,r,s;if(e===Ai){const e=t.readUInt8();e===Ci.TXID_ONLY?s=Oi.fromTxid(Tt(t.readReverse(32))):(e===Ci.RAWTX_AND_BUMP_INDEX&&(r=t.readVarIntNum()),i=Li.fromReader(t),s=Oi.fromTx(i,r))}else i=Li.fromReader(t),r=0!==t.readUInt8()?t.readVarIntNum():void 0,s=Oi.fromTx(i,r);return s}}function xi(t){if(null==t)throw new Error("Expected a valid value, but got undefined.");return t}const Ni=4022206465,Ai=4022206466,Ti=16843009;var Ci,Ri;!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"}(Ci||(Ci={}));class Bi{bumps=[];txs=[];version=Ai;atomicTxid=void 0;txidIndex=void 0;constructor(t=Ai){this.version=t}findTxid(t){return this.ensureTxidIndex().get(t)}ensureTxidIndex(){if(null==this.txidIndex){this.txidIndex=new Map;for(const t of this.txs)this.txidIndex.set(t.txid,t)}return this.txidIndex}deleteFromIndex(t){this.txidIndex?.delete(t)}addToIndex(t){this.txidIndex?.set(t.txid,t)}makeTxidOnly(t){const e=this.txs.findIndex((e=>e.txid===t));if(-1===e)return;let i=this.txs[e];return i.isTxidOnly||(this.deleteFromIndex(t),this.txs.splice(e,1),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(xi(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(xi(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 s of i.path[0])if(s.hash===r){t.bumpIndex=e,s.txid=!0;break}}return e}mergeRawTx(t,e){const i=new Oi(t,e);return this.removeExistingTxid(i.txid),this.txs.push(i),this.addToIndex(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 Oi(t,i);if(this.txs.push(r),this.addToIndex(r),this.tryToValidateBumpIndex(r),i=r.bumpIndex,void 0===i)for(const e of t.inputs)null!=e.sourceTransaction&&this.mergeTransaction(e.sourceTransaction);return r}removeExistingTxid(t){const e=this.txs.findIndex((e=>e.txid===t));e>=0&&(this.deleteFromIndex(t),this.txs.splice(e,1))}mergeTxidOnly(t){let e=this.findTxid(t);return null==e&&(e=new Oi(t),this.txs.push(e),this.addToIndex(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)?Bi.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 s=(t,i)=>{const r=t.computeRoot(i);return void 0!==e.roots[t.blockHeight]&&""!==e.roots[t.blockHeight]||(e.roots[t.blockHeight]=r),e.roots[t.blockHeight]===r};for(const t of this.bumps)for(const i of t.path[0])if(!0===i.txid&&"string"==typeof i.hash&&i.hash.length>0&&(r[i.hash]=!0,!s(t,i.hash)))return e;for(const t of this.txs)if(void 0!==t.bumpIndex&&null==this.bumps[t.bumpIndex].path[0].find((e=>e.hash===t.txid)))return e;for(const t of this.txs){for(const i of t.inputTxids)if(!r[i])return e;r[t.txid]=!0}return e.valid=!0,e}toWriter(t){t.writeUInt32LE(this.version),t.writeVarIntNum(this.bumps.length);for(const e of this.bumps)t.write(e.toBinary());t.writeVarIntNum(this.txs.length);for(const e of this.txs)e.toWriter(t,this.version)}toBinary(){this.sortTxs();const t=new Kt;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 Kt;return r.writeUInt32LE(Ti),r.writeReverse(Ct(t,"hex")),i.toWriter(r),r.toArray()}toHex(){return Tt(this.toBinary())}static fromReader(t){let e,i=t.readUInt32LE();if(i===Ti&&(e=Tt(t.readReverse(32)),i=t.readUInt32LE()),i!==Ni&&i!==Ai)throw new Error(`Serialized BEEF must start with 4022206465 or ${Ai} but starts with ${i}`);const r=new Bi(i),s=t.readVarIntNum();for(let e=0;e<s;e++){const e=Pi.fromReader(t,!1);r.bumps.push(e)}const n=t.readVarIntNum();for(let e=0;e<n;e++){const e=Oi.fromReader(t,i);r.txs.push(e)}return r.atomicTxid=e,r}static fromBinary(t){const e=new $t(t);return Bi.fromReader(e)}static fromString(t,e="hex"){const i=Ct(t,e),r=new $t(i);return Bi.fromReader(r)}tryToValidateBumpIndex(t){if(void 0!==t.bumpIndex)return!0;const e=t.txid;for(let i=0;i<this.bumps.length;i++){const r=this.bumps[i].path[0].findIndex((t=>t.hash===e));if(r>=0)return t.bumpIndex=i,this.bumps[i].path[0][r].txid=!0,!0}return!1}sortTxs(){const t={},e={};let i=[];const r=[],s=[];for(const n of this.txs)e[n.txid]=n,n.isValid=n.hasProof,n.isValid?(t[n.txid]=!0,r.push(n)):n.isTxidOnly&&0===n.inputTxids.length?(t[n.txid]=!0,s.push(n)):i.push(n);const n={},a=[],o=i;i=[];for(const t of o){let r=!1;for(const i of t.inputTxids)void 0===e[i]&&(n[i]=!0,r=!0);r?a.push(t):i.push(t)}for(;i.length>0;){const e=i;i=[];for(const s of e)s.inputTxids.every((e=>t[e]))?(t[s.txid]=!0,r.push(s)):i.push(s);if(e.length===i.length)break}const c=i;return this.txs=a.concat(c).concat(s).concat(r),{missingInputs:Object.keys(n),notValid:c.map((t=>t.txid)),valid:Object.keys(t),withMissingInputs:a.map((t=>t.txid)),txidOnly:s.map((t=>t.txid))}}clone(){const t=new Bi;return t.version=this.version,t.bumps=Array.from(this.bumps),t.txs=Array.from(this.txs),t.txidIndex=void 0,t}trimKnownTxids(t){for(let e=0;e<this.txs.length;){const i=this.txs[e];i.isTxidOnly&&t.includes(i.txid)?(this.deleteFromIndex(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 s=e.path[i-1].find((t=>t.offset===r.offset+1)),n=r.offset>>1;void 0!==s&&"string"==typeof s.hash&&e.path[i].every((t=>t.offset!==n))&&e.path[i].push({offset:n,hash:(t=s.hash+r.hash,Tt(K(Ct(t,"hex").reverse()).reverse()))})}var t}}class Li{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}=Li.fromAnyBeef(t,e);return i}static fromAtomicBEEF(t){const{tx:e,txid:i,beef:r}=Li.fromAnyBeef(t);if(i!==r.atomicTxid)throw null!=r.atomicTxid?new Error(`Transaction with TXID ${r.atomicTxid} not found in BEEF data.`):new Error("beef must conform to BRC-95 and must contain the subject txid.");return e}static fromAnyBeef(t,e){const i=Bi.fromBinary(t);if(i.txs.length<1)throw new Error("beef must include at least one transaction.");const r=e??i.atomicTxid??i.txs.slice(-1)[0].txid,s=i.findAtomicTransaction(r);if(null==s)throw null!=e?new Error(`Transaction with TXID ${r} not found in BEEF data.`):new Error("beef does not contain transaction for atomic txid.");return{tx:s,beef:i,txid:r}}static fromEF(t){const e=new $t(t),i=e.readUInt32LE();if("0000000000ef"!==Tt(e.read(6)))throw new Error("Invalid EF marker");const r=e.readVarIntNum(),s=[];for(let t=0;t<r;t++){const t=Tt(e.readReverse(32)),i=e.readUInt32LE(),r=e.readVarIntNum(),n=e.read(r),a=ai.fromBinary(n),o=e.readUInt32LE(),c=e.readUInt64LEBn().toNumber(),h=e.readVarIntNum(),d=e.read(h),u=ni.fromBinary(d),l=new Li(void 0,[],[],void 0);l.outputs=Array(i+1).fill(null),l.outputs[i]={satoshis:c,lockingScript:u},s.push({sourceTransaction:l,sourceTXID:t,sourceOutputIndex:i,unlockingScript:a,sequence:o})}const n=e.readVarIntNum(),a=[];for(let t=0;t<n;t++){const t=e.readUInt64LEBn().toNumber(),i=e.readVarIntNum(),r=e.read(i),s=ni.fromBinary(r);a.push({satoshis:t,lockingScript:s})}const o=e.readUInt32LE();return new Li(i,s,a,o)}static parseScriptOffsets(t){const e=new $t(t),i=[],r=[];e.pos+=4;const s=e.readVarIntNum();for(let t=0;t<s;t++){e.pos+=36;const r=e.readVarIntNum();i.push({vin:t,offset:e.pos,length:r}),e.pos+=r+4}const n=e.readVarIntNum();for(let t=0;t<n;t++){e.pos+=8;const i=e.readVarIntNum();r.push({vout:t,offset:e.pos,length:i}),e.pos+=i}return{inputs:i,outputs:r}}static fromReader(t){const e=t.readUInt32LE(),i=t.readVarIntNum(),r=[];for(let e=0;e<i;e++){const e=Tt(t.readReverse(32)),i=t.readUInt32LE(),s=t.readVarIntNum(),n=t.read(s),a=ai.fromBinary(n),o=t.readUInt32LE();r.push({sourceTXID:e,sourceOutputIndex:i,unlockingScript:a,sequence:o})}const s=t.readVarIntNum(),n=[];for(let e=0;e<s;e++){const e=t.readUInt64LEBn().toNumber(),i=t.readVarIntNum(),r=t.read(i),s=ni.fromBinary(r);n.push({satoshis:e,lockingScript:s})}const a=t.readUInt32LE();return new Li(e,r,n,a)}static fromBinary(t){const e=new $t(t);return Li.fromReader(e)}static fromHex(t){return Li.fromBinary(Ct(t,"hex"))}static fromHexEF(t){return Li.fromEF(Ct(t,"hex"))}static fromHexBEEF(t,e){return Li.fromBEEF(Ct(t,"hex"),e)}constructor(t=1,e=[],i=[],r=0,s=new Map,n){this.version=t,this.inputs=e,this.outputs=i,this.lockTime=r,this.metadata=s,this.merklePath=n}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 bi).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=wi.getInstance(),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 s=Array(e.length).fill(1);r-=e.length,i+=e.length;for(let t=0;t<e.length-1;t++){const e=this.benfordNumber(0,r);s[t]=s[t]+e,i+=e,r-=e}for(const t of this.outputs)!0===t.change&&(t.satoshis=s.shift());return i}distributeEqualChange(t,e){let i=0;const r=Math.floor(t/e.length);for(const t of e)i+=r,t.satoshis=r;return i}benfordNumber(t,e){const i=Math.floor(9*Math.random())+1;return Math.floor(t+(e-t)*Math.log10(1+1/i)/Math.log10(10))}getFee(){let t=0;for(const e of this.inputs){if("object"!=typeof e.sourceTransaction)throw new Error("Source transactions or sourceSatoshis are required for all inputs to calculate fee");t+=e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0}let e=0;for(const t of this.outputs)e+=t.satoshis??0;return t-e}async sign(){this.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 Ei(t?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",e)}()){return await t.broadcast(this)}toBinary(){const t=new Kt;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(Ct(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 Kt;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(Ct(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 Tt(this.toEF())}toHex(){return Tt(this.toBinary())}toHexBEEF(){return Tt(this.toBEEF())}toHexAtomicBEEF(){return Tt(this.toAtomicBEEF())}hash(t){let e;return null!=this.cachedHash?e=this.cachedHash:(e=K(this.toBinary()),this.cachedHash=e),"hex"===t?Tt(e):e}id(t){const e=[...this.hash()];return e.reverse(),"hex"===t?Tt(e):e}async verify(t=function(){return new _i}(),e,i){const r=new Set,s=[this];for(;s.length>0;){const n=s.shift(),a=n?.id("hex")??"";if(null!=a&&""!==a&&r.has(a))continue;if("object"==typeof n?.merklePath){if("scripts only"===t){null!=a&&r.add(a);continue}if(await n.merklePath.verify(a,t)){r.add(a);continue}throw new Error(`Invalid merkle path for transaction ${a}`)}if(void 0!==e){if(void 0===n)throw new Error("Transaction is undefined");const t=Li.fromEF(n.toEF());if(delete t.outputs[0].satoshis,t.outputs[0].change=!0,await t.fee(e),n.getFee()<t.getFee())throw new Error(`Verification failed because the transaction ${a} has an insufficient fee and has not been mined.`)}let o=0;if(void 0===n)throw new Error("Transaction is undefined");for(let t=0;t<n.inputs.length;t++){const e=n.inputs[t];if("object"!=typeof e.sourceTransaction)throw new Error(`Verification failed because the input at index ${t} of transaction ${a} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if("object"!=typeof e.unlockingScript)throw new Error(`Verification failed because the input at index ${t} of transaction ${a} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);const c=e.sourceTransaction.outputs[e.sourceOutputIndex];o+=c.satoshis??0;const h=e.sourceTransaction.id("hex");r.has(h)||s.push(e.sourceTransaction);const d=n.inputs.filter(((e,i)=>i!==t));if(void 0===e.sourceTXID&&(e.sourceTXID=h),!new fi({sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:n.version,otherInputs:d,unlockingScript:e.unlockingScript,inputSequence:e.sequence??0,inputIndex:t,outputs:n.outputs,lockTime:n.lockTime,memoryLimit:i}).validate())return!1}let c=0;for(const t of n.outputs){if("number"!=typeof t.satoshis)throw new Error("Every output must have a defined amount during transaction verification.");c+=t.satoshis}if(c>o)return!1;r.add(a)}return!0}toBEEF(t){const e=new Kt;e.writeUInt32LE(Ni);const i=[],r=new Map,s=new Map,n=[],a=new Set,o=e=>{const c=e.id("hex");if(a.has(c))return;const h={tx:e},d=e.merklePath,u="object"==typeof d;if(u&&null!=d&&(h.pathIndex=(t=>{const e=r.get(t);if(void 0!==e)return e;const n=`${t.blockHeight}:${t.computeRoot()}`,a=s.get(n);if(void 0!==a)return i[a].combine(t),r.set(t,a),a;const o=i.length;return i.push(t),r.set(t,o),s.set(n,o),o})(d)),!u)for(let i=e.inputs.length-1;i>=0;i--){const r=e.inputs[i];if("object"==typeof r.sourceTransaction)o(r.sourceTransaction);else if(!1===t)throw new Error("A required source transaction is missing!")}a.add(c),n.push(h)};o(this),e.writeVarIntNum(i.length);for(const t of i)e.write(t.toBinary());e.writeVarIntNum(n.length);for(const t of n)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 Kt;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"}(Ri||(Ri={}));class Mi{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(t,e,i){this.cacheSharedSecret=e,this.retrieveCachedSharedSecret=i,this.anyone=new Ce(1).toPublicKey(),this.rootKey="anyone"===t?new Ce(1):t,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(t,e,i,r=!1){return i=this.normalizeCounterparty(i),r?this.rootKey.deriveChild(i,this.computeInvoiceNumber(t,e),this.cacheSharedSecret,this.retrieveCachedSharedSecret).toPublicKey():i.deriveChild(this.rootKey,this.computeInvoiceNumber(t,e),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}derivePrivateKey(t,e,i){return i=this.normalizeCounterparty(i),this.rootKey.deriveChild(i,this.computeInvoiceNumber(t,e),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}deriveSymmetricKey(t,e,i){i="anyone"===i?this.anyone:this.normalizeCounterparty(i);const r=this.derivePublicKey(t,e,i),s=this.derivePrivateKey(t,e,i);return new Qe(s.deriveSharedSecret(r)?.x?.toArray()??[])}revealCounterpartySecret(t){if("self"===t)throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");t=this.normalizeCounterparty(t);const e=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(e,"test").toHex()===this.rootKey.deriveChild(t,"test").toHex())throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(t).encode(!0)}revealSpecificSecret(t,e,i){t=this.normalizeCounterparty(t);const r=this.rootKey.deriveSharedSecret(t),s=Ct(this.computeInvoiceNumber(e,i),"utf8");return j(r.encode(!0),s)}normalizeCounterparty(t){if(null==t)throw new Error("counterparty must be self, anyone or a public key!");return"self"===t?this.rootKey.toPublicKey():"anyone"===t?new Ce(1).toPublicKey():"string"==typeof t?_e.fromString(t):t}computeInvoiceNumber(t,e){const i=t[0];if(!Number.isInteger(i)||i<0||i>2)throw new Error("Protocol security level must be 0, 1, or 2");const r=t[1].toLowerCase().trim();if(e.length>800)throw new Error("Key IDs must be 800 characters or less");if(e.length<1)throw new Error("Key IDs must be 1 character or more");if(r.length>400){if(!r.startsWith("specific linkage revelation "))throw new Error("Protocol names must be 400 characters or less");if(r.length>430)throw new Error("Specific linkage revelation protocol names must be 430 characters or less")}if(r.length<5)throw new Error("Protocol names must be 5 characters or more");if(r.includes(" "))throw new Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(r))throw new Error("Protocol names can only contain letters, numbers and spaces");if(r.endsWith(" protocol"))throw new Error('No need to end your protocol name with " protocol"');return`${i}-${r}-${e}`}}class Di{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(t,e){this.rootKey="anyone"===t?new Ce(1):t,this.keyDeriver=new Mi(this.rootKey,((t,e,i)=>{this.cacheSet(`${t.toString()}-${e.toString()}`,i)}),((t,e)=>this.cacheGet(`${t.toString()}-${e.toString()}`))),this.identityKey=this.rootKey.toPublicKey().toString(),this.cache=new Map;const i=e?.maxCacheSize;this.maxCacheSize=null!=i&&!isNaN(i)&&i>0?i:1e3}derivePublicKey(t,e,i,r=!1){const s=this.generateCacheKey("derivePublicKey",t,e,i,r);if(this.cache.has(s)){const t=this.cacheGet(s);if(void 0===t)throw new Error("Cached value is undefined");return t}{const n=this.keyDeriver.derivePublicKey(t,e,i,r);return this.cacheSet(s,n),n}}derivePrivateKey(t,e,i){const r=this.generateCacheKey("derivePrivateKey",t,e,i);if(this.cache.has(r)){const t=this.cacheGet(r);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.derivePrivateKey(t,e,i);return this.cacheSet(r,s),s}}deriveSymmetricKey(t,e,i){const r=this.generateCacheKey("deriveSymmetricKey",t,e,i);if(this.cache.has(r)){const t=this.cacheGet(r);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.deriveSymmetricKey(t,e,i);return this.cacheSet(r,s),s}}revealCounterpartySecret(t){const e=this.generateCacheKey("revealCounterpartySecret",t);if(this.cache.has(e)){const t=this.cacheGet(e);if(void 0===t)throw new Error("Cached value is undefined");return t}{const i=this.keyDeriver.revealCounterpartySecret(t);return this.cacheSet(e,i),i}}revealSpecificSecret(t,e,i){const r=this.generateCacheKey("revealSpecificSecret",t,e,i);if(this.cache.has(r)){const t=this.cacheGet(r);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.revealSpecificSecret(t,e,i);return this.cacheSet(r,s),s}}generateCacheKey(t,...e){return`${t}|${e.map((t=>this.serializeArgument(t))).join("|")}`}serializeArgument(t){return t instanceof _e||t instanceof Ce?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 Fi=class{keyDeriver;constructor(t){"string"!=typeof t.identityKey&&(t=new Di(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 ei).generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),_e.fromString(t.counterparty),fe.fromDER(i)),s=[...r.R.encode(!0),...r.SPrime.encode(!0),...r.z.toArray()],n=(new Date).toISOString(),{ciphertext:a}=await this.encrypt({plaintext:i,protocolID:[2,"counterparty linkage revelation"],keyID:n,counterparty:t.verifier}),{ciphertext:o}=await this.encrypt({plaintext:s,protocolID:[2,"counterparty linkage revelation"],keyID:n,counterparty:t.verifier});return{prover:e,verifier:t.verifier,counterparty:t.counterparty,revelationTime:n,encryptedLinkage:a,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(t){const{publicKey:e}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const i=this.keyDeriver.revealSpecificSecret(t.counterparty,t.protocolID,t.keyID),{ciphertext:r}=await this.encrypt({plaintext:i,protocolID:[2,`specific linkage revelation ${t.protocolID[0]} ${t.protocolID[1]}`],keyID:t.keyID,counterparty:t.verifier}),{ciphertext:s}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${t.protocolID[0]} ${t.protocolID[1]}`],keyID:t.keyID,counterparty:t.verifier});return{prover:e,verifier:t.verifier,counterparty:t.counterparty,protocolID:t.protocolID,keyID:t.keyID,encryptedLinkage:r,encryptedLinkageProof:s,proofType:0}}async encrypt(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self").encrypt(t.plaintext)}}async decrypt(t,e){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self").decrypt(t.ciphertext)}}async createHmac(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const e=this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self");return{hmac:j(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=j(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??U(t.data??[]),i=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePrivateKey(t.protocolID,t.keyID,t.counterparty??"anyone");return{signature:Se(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??U(t.data??[]),i=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePublicKey(t.protocolID,t.keyID,t.counterparty??"self",t.forSelf),s=Ee(new r(e),ge.fromDER(t.signature),i);if(!s){const t=new Error("Signature is not valid");throw t.code="ERR_INVALID_SIGNATURE",t}return{valid:s}}};class Vi{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 Hi 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 qi,Ui,Ki;!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"}(qi||(qi={}));class $i{domain;constructor(t="*"){if("object"!=typeof window)throw new Error("The XDM substrate requires a global window object.");if("function"!=typeof window.postMessage)throw new Error("The window object does not seem to support postMessage calls.");this.domain=t}async invoke(t,e){return await new Promise(((i,r)=>{const s=Dt(xe(12)),n=t=>{if("CWI"===t.data.type&&t.isTrusted&&t.data.id===s&&!0!==t.data.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",n),"error"===t.data.status){const e=new Hi(t.data.description,t.data.code);r(e)}else i(t.data.result)};window.addEventListener("message",n),window.parent.postMessage({type:"CWI",isInvocation:!0,id:s,call:t,args:e},this.domain)}))}async createAction(t){return await this.invoke("createAction",t)}async signAction(t){return await this.invoke("signAction",t)}async abortAction(t){return await this.invoke("abortAction",t)}async listActions(t){return await this.invoke("listActions",t)}async internalizeAction(t){return await this.invoke("internalizeAction",t)}async listOutputs(t){return await this.invoke("listOutputs",t)}async relinquishOutput(t){return await this.invoke("relinquishOutput",t)}async getPublicKey(t){return await this.invoke("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.invoke("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.invoke("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.invoke("encrypt",t)}async decrypt(t){return await this.invoke("decrypt",t)}async createHmac(t){return await this.invoke("createHmac",t)}async verifyHmac(t){return await this.invoke("verifyHmac",t)}async createSignature(t){return await this.invoke("createSignature",t)}async verifySignature(t){return await this.invoke("verifySignature",t)}async acquireCertificate(t){return await this.invoke("acquireCertificate",t)}async listCertificates(t){return await this.invoke("listCertificates",t)}async proveCertificate(t){return await this.invoke("proveCertificate",t)}async relinquishCertificate(t){return await this.invoke("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.invoke("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.invoke("discoverByAttributes",t)}async isAuthenticated(t){return await this.invoke("isAuthenticated",t)}async waitForAuthentication(t){return await this.invoke("waitForAuthentication",t)}async getHeight(t){return await this.invoke("getHeight",t)}async getHeaderForHeight(t){return await this.invoke("getHeaderForHeight",t)}async getNetwork(t){return await this.invoke("getNetwork",t)}async getVersion(t){return await this.invoke("getVersion",t)}}class ji{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(t,e,i,r,s,n,a){this.type=t,this.serialNumber=e,this.subject=i,this.certifier=r,this.revocationOutpoint=s,this.fields=n,this.signature=a}toBinary(t=!0){const e=new Kt,i=Ct(this.type,"base64");e.write(i);const r=Ct(this.serialNumber,"base64");e.write(r);const s=Ct(this.subject,"hex");e.write(s);const n=Ct(this.certifier,"hex");e.write(n);const[a,o]=this.revocationOutpoint.split("."),c=Ct(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=Ct(t,"utf8");e.writeVarIntNum(r.length),e.write(r);const s=Ct(i,"utf8");e.writeVarIntNum(s.length),e.write(s)}if(t&&(this.signature??"").length>0){const t=Ct(this.signature,"hex");e.write(t)}return e.toArray()}static fromBinary(t){const e=new $t(t),i=Dt(e.read(32)),r=Dt(e.read(32)),s=e.read(33),n=Tt(s),a=e.read(33),o=Tt(a),c=e.read(32),h=`${Tt(c)}.${e.readVarIntNum()}`,d=e.readVarIntNum(),u={};for(let t=0;t<d;t++){const t=e.readVarIntNum(),i=e.read(t),r=Lt(i),s=e.readVarIntNum(),n=e.read(s),a=Lt(n);u[r]=a}let l;if(!e.eof()){const t=e.read();l=ge.fromDER(t).toString("hex")}return new ji(i,r,n,o,h,u,l)}async verify(){const t=new Fi("anyone"),e=this.toBinary(!1),i=this.signature??"",{valid:r}=await t.verifySignature({signature:Ct(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=Tt(i)}static getCertificateFieldEncryptionDetails(t,e){return{protocolID:[2,"certificate field encryption"],keyID:e?`${e} ${t}`:t}}}(Ki=Ui||(Ui={}))[Ki.createAction=1]="createAction",Ki[Ki.signAction=2]="signAction",Ki[Ki.abortAction=3]="abortAction",Ki[Ki.listActions=4]="listActions",Ki[Ki.internalizeAction=5]="internalizeAction",Ki[Ki.listOutputs=6]="listOutputs",Ki[Ki.relinquishOutput=7]="relinquishOutput",Ki[Ki.getPublicKey=8]="getPublicKey",Ki[Ki.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",Ki[Ki.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",Ki[Ki.encrypt=11]="encrypt",Ki[Ki.decrypt=12]="decrypt",Ki[Ki.createHmac=13]="createHmac",Ki[Ki.verifyHmac=14]="verifyHmac",Ki[Ki.createSignature=15]="createSignature",Ki[Ki.verifySignature=16]="verifySignature",Ki[Ki.acquireCertificate=17]="acquireCertificate",Ki[Ki.listCertificates=18]="listCertificates",Ki[Ki.proveCertificate=19]="proveCertificate",Ki[Ki.relinquishCertificate=20]="relinquishCertificate",Ki[Ki.discoverByIdentityKey=21]="discoverByIdentityKey",Ki[Ki.discoverByAttributes=22]="discoverByAttributes",Ki[Ki.isAuthenticated=23]="isAuthenticated",Ki[Ki.waitForAuthentication=24]="waitForAuthentication",Ki[Ki.getHeight=25]="getHeight",Ki[Ki.getHeaderForHeight=26]="getHeaderForHeight",Ki[Ki.getNetwork=27]="getNetwork",Ki[Ki.getVersion=28]="getVersion";const zi=Ui;class Wi{wire;constructor(t){this.wire=t}async transmit(t,e="",i=[]){const r=new Kt;r.writeUInt8(zi[t]);const s=Ct(e,"utf8");r.writeUInt8(s.length),r.write(s),i.length>0&&r.write(i);const n=r.toArray(),a=await this.wire.transmitToWallet(n),o=new $t(a),c=o.readUInt8();if(0===c)return o.read();{const t=o.readVarIntNum(),e=o.read(t),i=Lt(e),r=o.readVarIntNum(),s=o.read(r),n=Lt(s);throw new Hi(i,c,n)}}async createAction(t,e){const i=new Kt,r=Ct(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=Ct(e.unlockingScript,"hex");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1),i.writeVarIntNum(e.unlockingScriptLength??0);const t=Ct(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=Ct(e.lockingScript,"hex");i.writeVarIntNum(t.length),i.write(t),i.writeVarIntNum(e.satoshis);const r=Ct(e.outputDescription,"utf8");if(i.writeVarIntNum(r.length),i.write(r),null!=e.basket&&""!==e.basket){const t=Ct(e.basket,"utf8");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1);if(null!=e.customInstructions&&""!==e.customInstructions){const t=Ct(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=Ct(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=Ct(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=Ct(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=Ct(e,"hex");i.write(t)}}else i.writeVarIntNum(-1);"boolean"==typeof t.options.randomizeOutputs?i.writeInt8(t.options.randomizeOutputs?1:0):i.writeInt8(-1)}else i.writeInt8(0);const s=await this.transmit("createAction",e,i.toArray()),n=new $t(s),a={};if(1===n.readInt8()){const t=n.read(32);a.txid=Tt(t)}if(1===n.readInt8()){const t=n.readVarIntNum();a.tx=n.read(t)}const o=n.readVarIntNum();if(o>=0){a.noSendChange=[];for(let t=0;t<o;t++){const t=this.readOutpoint(n);a.noSendChange.push(t)}}const c=n.readVarIntNum();if(c>=0){a.sendWithResults=[];for(let t=0;t<c;t++){const t=n.read(32),e=Tt(t),i=n.readInt8();let r="unproven";1===i?r="unproven":2===i?r="sending":3===i&&(r="failed"),a.sendWithResults.push({txid:e,status:r})}}if(1===n.readInt8()){const t=n.readVarIntNum(),e=n.read(t),i=n.readVarIntNum(),r=n.read(i);a.signableTransaction={tx:e,reference:Dt(r)}}return a}async signAction(t,e){const i=new Kt,r=Object.keys(t.spends);i.writeVarIntNum(r.length);for(const e of r){i.writeVarIntNum(Number(e));const r=t.spends[Number(e)],s=Ct(r.unlockingScript,"hex");i.writeVarIntNum(s.length),i.write(s),"number"==typeof r.sequenceNumber?i.writeVarIntNum(r.sequenceNumber):i.writeVarIntNum(-1)}const s=Ct(t.reference,"base64");if(i.writeVarIntNum(s.length),i.write(s),null!=t.options)if(i.writeInt8(1),"boolean"==typeof t.options.acceptDelayedBroadcast?i.writeInt8(t.options.acceptDelayedBroadcast?1:0):i.writeInt8(-1),"boolean"==typeof t.options.returnTXIDOnly?i.writeInt8(t.options.returnTXIDOnly?1:0):i.writeInt8(-1),"boolean"==typeof t.options.noSend?i.writeInt8(t.options.noSend?1:0):i.writeInt8(-1),null!=t.options.sendWith){i.writeVarIntNum(t.options.sendWith.length);for(const e of t.options.sendWith){const t=Ct(e,"hex");i.write(t)}}else i.writeVarIntNum(-1);else i.writeInt8(0);const n=await this.transmit("signAction",e,i.toArray()),a=new $t(n),o={};if(1===a.readInt8()){const t=a.read(32);o.txid=Tt(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=Tt(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,Ct(t.reference,"base64")),{aborted:!0}}async listActions(t,e){const i=new Kt;i.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Ct(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}"any"===t.labelQueryMode?i.writeInt8(1):"all"===t.labelQueryMode?i.writeInt8(2):i.writeInt8(-1);const r=[t.includeLabels,t.includeInputs,t.includeInputSourceLockingScripts,t.includeInputUnlockingScripts,t.includeOutputs,t.includeOutputLockingScripts];for(const t of r)"boolean"==typeof t?i.writeInt8(t?1:0):i.writeInt8(-1);"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const s=await this.transmit("listActions",e,i.toArray()),n=new $t(s),a=n.readVarIntNum(),o=[];for(let t=0;t<a;t++){const t=n.read(32),e=Tt(t),i=n.readVarIntNum(),r=n.readInt8();let s;switch(r){case 1:s="completed";break;case 2:s="unprocessed";break;case 3:s="sending";break;case 4:s="unproven";break;case 5:s="unsigned";break;case 6:s="nosend";break;case 7:s="nonfinal";break;case 8:s="failed";break;default:throw new Error(`Unknown status code: ${r}`)}const a=1===n.readInt8(),c=n.readVarIntNum(),h=n.read(c),d={txid:e,satoshis:i,status:s,isOutgoing:a,description:Lt(h),version:0,lockTime:0},u=n.readVarIntNum();if(u>=0){d.labels=[];for(let t=0;t<u;t++){const t=n.readVarIntNum(),e=n.read(t);d.labels.push(Lt(e))}}d.version=n.readVarIntNum(),d.lockTime=n.readVarIntNum();const l=n.readVarIntNum();if(l>=0){d.inputs=[];for(let t=0;t<l;t++){const t=this.readOutpoint(n),e=n.readVarIntNum(),i=n.readVarIntNum();let r;if(i>=0){const t=n.read(i);r=Tt(t)}const s=n.readVarIntNum();let a;if(s>=0){const t=n.read(s);a=Tt(t)}const o=n.readVarIntNum(),c=n.read(o),h=Lt(c),u=n.readVarIntNum();d.inputs.push({sourceOutpoint:t,sourceSatoshis:e,sourceLockingScript:r,unlockingScript:a,inputDescription:h,sequenceNumber:u})}}const f=n.readVarIntNum();if(f>=0){d.outputs=[];for(let t=0;t<f;t++){const t=n.readVarIntNum(),e=n.readVarIntNum(),i=n.readVarIntNum();let r;if(i>=0){const t=n.read(i);r=Tt(t)}const s=1===n.readInt8(),a=n.readVarIntNum(),o=n.read(a),c=Lt(o),h=n.readVarIntNum();let u;if(h>=0){const t=n.read(h);u=Lt(t)}const l=n.readVarIntNum(),f=[];if(l>=0)for(let t=0;t<l;t++){const t=n.readVarIntNum(),e=n.read(t);f.push(Lt(e))}const p=n.readVarIntNum();let b;if(p>=0){const t=n.read(p);b=Lt(t)}d.outputs.push({outputIndex:t,satoshis:e,lockingScript:r,spendable:s,outputDescription:c,basket:u,tags:f,customInstructions:b})}}o.push(d)}return{totalActions:a,actions:o}}async internalizeAction(t,e){const i=new Kt;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(Ct(e.paymentRemittance.senderIdentityKey,"hex"));const t=Ct(e.paymentRemittance.derivationPrefix,"base64");i.writeVarIntNum(t.length),i.write(t);const r=Ct(e.paymentRemittance.derivationSuffix,"base64");i.writeVarIntNum(r.length),i.write(r)}else{i.writeUInt8(2);const t=Ct(e.insertionRemittance?.basket,"utf8");if(i.writeVarIntNum(t.length),i.write(t),"string"==typeof e.insertionRemittance?.customInstructions&&""!==e.insertionRemittance.customInstructions){const t=Ct(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=Ct(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=Ct(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}}else i.writeVarIntNum(-1);const r=Ct(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 Kt,r=Ct(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=Ct(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}}else i.writeVarIntNum(0);"all"===t.tagQueryMode?i.writeInt8(1):"any"===t.tagQueryMode?i.writeInt8(2):i.writeInt8(-1),"locking scripts"===t.include?i.writeInt8(1):"entire transactions"===t.include?i.writeInt8(2):i.writeInt8(-1),"boolean"==typeof t.includeCustomInstructions?i.writeInt8(t.includeCustomInstructions?1:0):i.writeInt8(-1),"boolean"==typeof t.includeTags?i.writeInt8(t.includeTags?1:0):i.writeInt8(-1),"boolean"==typeof t.includeLabels?i.writeInt8(t.includeLabels?1:0):i.writeInt8(-1),"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const s=await this.transmit("listOutputs",e,i.toArray()),n=new $t(s),a=n.readVarIntNum(),o=n.readVarIntNum();let c;o>=0&&(c=n.read(o));const h=[];for(let t=0;t<a;t++){const t={spendable:!0,outpoint:this.readOutpoint(n),satoshis:n.readVarIntNum()},e=n.readVarIntNum();e>=0&&(t.lockingScript=Tt(n.read(e)));const i=n.readVarIntNum();i>=0&&(t.customInstructions=Lt(n.read(i)));const r=n.readVarIntNum();if(-1!==r){const e=[];for(let t=0;t<r;t++){const t=n.readVarIntNum();e.push(Lt(n.read(t)))}t.tags=e}const s=n.readVarIntNum();if(-1!==s){const e=[];for(let t=0;t<s;t++){const t=n.readVarIntNum();e.push(Lt(n.read(t)))}t.labels=e}h.push(t)}return{totalOutputs:a,BEEF:c,outputs:h}}async relinquishOutput(t,e){const i=new Kt,r=Ct(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 Kt,[i,r]=t.split(".");return e.write(Ct(i,"hex")),e.writeVarIntNum(Number(r)),e.toArray()}readOutpoint(t){return`${Tt(t.read(32))}.${t.readVarIntNum()}`}async getPublicKey(t,e){const i=new Kt;i.writeUInt8(t.identityKey?1:0),t.identityKey?i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)):(i.write(this.encodeKeyRelatedParams(t.protocolID??=[Ri.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:Tt(r)}}async revealCounterpartyKeyLinkage(t,e){const i=new Kt;i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),i.write(Ct(t.counterparty,"hex")),i.write(Ct(t.verifier,"hex"));const r=await this.transmit("revealCounterpartyKeyLinkage",e,i.toArray()),s=new $t(r),n=Tt(s.read(33)),a=Tt(s.read(33)),o=Tt(s.read(33)),c=s.readVarIntNum(),h=Lt(s.read(c)),d=s.readVarIntNum(),u=s.read(d),l=s.readVarIntNum();return{prover:n,verifier:a,counterparty:o,revelationTime:h,encryptedLinkage:u,encryptedLinkageProof:s.read(l)}}async revealSpecificKeyLinkage(t,e){const i=new Kt;i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),i.write(Ct(t.verifier,"hex"));const r=await this.transmit("revealSpecificKeyLinkage",e,i.toArray()),s=new $t(r),n=Tt(s.read(33)),a=Tt(s.read(33)),o=Tt(s.read(33)),c=s.readUInt8(),h=s.readVarIntNum(),d=Lt(s.read(h)),u=s.readVarIntNum(),l=Lt(s.read(u)),f=s.readVarIntNum(),p=s.read(f),b=s.readVarIntNum();return{prover:n,verifier:a,counterparty:o,protocolID:[c,d],keyID:l,encryptedLinkage:p,encryptedLinkageProof:s.read(b),proofType:s.readUInt8()}}async encrypt(t,e){const i=new Kt;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 Kt;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 Kt;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 Kt;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 Kt;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 Kt;return i.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),"boolean"==typeof t.forSelf?i.writeInt8(t.forSelf?1:0):i.writeInt8(-1),i.writeVarIntNum(t.signature.length),i.write(t.signature),"object"==typeof t.data?(i.writeUInt8(1),i.writeVarIntNum(t.data.length),i.write(t.data)):(i.writeUInt8(2),i.write(t.hashToDirectlyVerify??[])),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),await this.transmit("verifySignature",e,i.toArray()),{valid:!0}}encodeKeyRelatedParams(t,e,i,r,s){const n=new Kt;n.writeUInt8(t[0]);const a=Ct(t[1],"utf8");n.writeVarIntNum(a.length),n.write(a);const o=Ct(e,"utf8");return n.writeVarIntNum(o.length),n.write(o),"string"!=typeof i?n.writeUInt8(0):"self"===i?n.writeUInt8(11):"anyone"===i?n.writeUInt8(12):n.write(Ct(i,"hex")),n.write(this.encodePrivilegedParams(r,s)),n.toArray()}async acquireCertificate(t,e){const i=new Kt;i.write(Ct(t.type,"base64")),i.write(Ct(t.certifier,"hex"));const r=Object.entries(t.fields);i.writeVarIntNum(r.length);for(const[t,e]of r){const r=Ct(t,"utf8"),s=Ct(e,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(s.length),i.write(s)}if(i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),i.writeUInt8("direct"===t.acquisitionProtocol?1:2),"direct"===t.acquisitionProtocol){i.write(Ct(t.serialNumber,"base64")),i.write(this.encodeOutpoint(t.revocationOutpoint??""));const e=Ct(t.signature,"hex");i.writeVarIntNum(e.length),i.write(e);const r="certifier"!==t.keyringRevealer?Ct(t.keyringRevealer,"hex"):[11];i.write(r);const s=Object.keys(t.keyringForSubject??{});i.writeVarIntNum(s.length);for(let e=0;e<s.length;e++){const r=Ct(s[e],"utf8");i.writeVarIntNum(r.length),i.write(r);const n=Ct(t.keyringForSubject?.[s[e]],"base64");i.writeVarIntNum(n.length),i.write(n)}}else{const e=Ct(t.certifierUrl,"utf8");i.writeVarIntNum(e.length),i.write(e)}const s=await this.transmit("acquireCertificate",e,i.toArray()),n=ji.fromBinary(s);return{...n,signature:n.signature}}encodePrivilegedParams(t,e){const i=new Kt;if("boolean"==typeof t?i.writeInt8(t?1:0):i.writeInt8(-1),"string"==typeof e){const t=Ct(e,"utf8");i.writeInt8(t.length),i.write(t)}else i.writeInt8(-1);return i.toArray()}async listCertificates(t,e){const i=new Kt;i.writeVarIntNum(t.certifiers.length);for(let e=0;e<t.certifiers.length;e++)i.write(Ct(t.certifiers[e],"hex"));i.writeVarIntNum(t.types.length);for(let e=0;e<t.types.length;e++)i.write(Ct(t.types[e],"base64"));"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason));const r=await this.transmit("listCertificates",e,i.toArray()),s=new $t(r),n=s.readVarIntNum(),a=[];for(let t=0;t<n;t++){const t=s.readVarIntNum(),e=s.read(t),i=ji.fromBinary(e),r={};if(1===s.readInt8()){const t=s.readVarIntNum();for(let e=0;e<t;e++){const t=s.readVarIntNum(),e=Lt(s.read(t)),i=s.readVarIntNum();r[e]=Dt(s.read(i))}}const n=s.readVarIntNum();let o;n>0&&(o=Lt(s.read(n))),a.push({...i,signature:i.signature,keyring:r,verifier:o})}return{totalCertificates:n,certificates:a}}async proveCertificate(t,e){const i=new Kt,r=Ct(t.certificate.type,"base64");i.write(r);const s=Ct(t.certificate.subject,"hex");i.write(s);const n=Ct(t.certificate.serialNumber,"base64");i.write(n);const a=Ct(t.certificate.certifier,"hex");i.write(a);const o=this.encodeOutpoint(t.certificate.revocationOutpoint??"");i.write(o);const c=Ct(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=Ct(t,"utf8"),s=Ct(e,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(s.length),i.write(s)}i.writeVarIntNum(t.fieldsToReveal.length);for(const e of t.fieldsToReveal){const t=Ct(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}i.write(Ct(t.verifier,"hex")),i.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason));const d=await this.transmit("proveCertificate",e,i.toArray()),u=new $t(d),l=u.readVarIntNum(),f={};for(let t=0;t<l;t++){const t=u.readVarIntNum(),e=Lt(u.read(t)),i=u.readVarIntNum();f[e]=Dt(u.read(i))}return{keyringForVerifier:f}}async relinquishCertificate(t,e){const i=new Kt,r=Ct(t.type,"base64");i.write(r);const s=Ct(t.serialNumber,"base64");i.write(s);const n=Ct(t.certifier,"hex");return i.write(n),await this.transmit("relinquishCertificate",e,i.toArray()),{relinquished:!0}}parseDiscoveryResult(t){const e=new $t(t),i=e.readVarIntNum(),r=[];for(let t=0;t<i;t++){const t=e.readVarIntNum(),i=e.read(t),s=ji.fromBinary(i),n=e.readVarIntNum(),a=Lt(e.read(n)),o=e.readVarIntNum(),c=Lt(e.read(o)),h=e.readVarIntNum(),d=Lt(e.read(h)),u=e.readUInt8(),l={},f=e.readVarIntNum();for(let t=0;t<f;t++){const t=e.readVarIntNum(),i=Lt(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=Lt(e.read(t)),r=e.readVarIntNum();p[i]=Lt(e.read(r))}r.push({...s,signature:s.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 Kt;i.write(Ct(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 Kt,r=Object.keys(t.attributes);i.writeVarIntNum(r.length);for(let e=0;e<r.length;e++)i.writeVarIntNum(r[e].length),i.write(Ct(r[e],"utf8")),i.writeVarIntNum(t.attributes[r[e]].length),i.write(Ct(t.attributes[r[e]],"utf8"));"number"==typeof t.limit?i.writeVarIntNum(t.limit):i.writeVarIntNum(-1),"number"==typeof t.offset?i.writeVarIntNum(t.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const s=await this.transmit("discoverByAttributes",e,i.toArray());return this.parseDiscoveryResult(s)}async isAuthenticated(t,e){return{authenticated:1===(await this.transmit("isAuthenticated",e))[0]}}async waitForAuthentication(t,e){return await this.transmit("waitForAuthentication",e),{authenticated:!0}}async getHeight(t,e){const i=await this.transmit("getHeight",e);return{height:new $t(i).readVarIntNum()}}async getHeaderForHeight(t,e){const i=new Kt;i.writeVarIntNum(t.height);const r=await this.transmit("getHeaderForHeight",e,i.toArray());return{header:Tt(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:Lt(i)}}}class Gi{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 $t(t),i=e.readUInt8(),r=zi[i];if(void 0===r||""===r)throw new Error(`Invalid call code: ${i}`);const s=e.readUInt8();let n;if(s>0){const t=e.read(s);n=Lt(t)}const a=e.read(),o=await fetch(`${this.baseUrl}/${r}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:n??""},body:new Uint8Array(a)}),c=await o.arrayBuffer();return Array.from(new Uint8Array(c))}}class Xi extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(t,e,i,r,s){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=t,this.sendWithResults=e,this.txid=i,this.tx=r,this.noSendChange=s,this.code=5,this.name=this.constructor.name}}class Ji{baseUrl;httpClient;originator;api;constructor(t,e="http://localhost:3321",i=fetch){this.baseUrl=e,this.originator=t,this.httpClient=i;const r="undefined"!=typeof window&&"undefined"!=typeof document&&"file://"!==window?.origin;this.api=async(t,e)=>{const s=!r&&this.originator?function(t,e="http"){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(t))try{return new URL(t).origin}catch{}try{return new URL(`${e}://${t}`).origin}catch{throw new Error(`Invalid originator value: ${t}`)}}(this.originator,"http"):void 0;r||void 0!==s||console.error("Originator is required in Node.js environments");const n=await await i(`${this.baseUrl}/${t}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...s?{Origin:s}:{},...s?{Originator:s}:{}},body:JSON.stringify(e)}),a=await n.json();if(!n.ok){if(400===n.status&&a.isError&&5===a.code)throw new Xi(a.reviewActionResults,a.sendWithResults,a.txid,a.tx,a.noSendChange);{const i={call:t,args:e,message:a.message??`HTTP Client error ${n.status}`};throw new Error(JSON.stringify(i))}}return a}}async createAction(t){return await this.api("createAction",t)}async signAction(t){return await this.api("signAction",t)}async abortAction(t){return await this.api("abortAction",t)}async listActions(t){return await this.api("listActions",t)}async internalizeAction(t){return await this.api("internalizeAction",t)}async listOutputs(t){return await this.api("listOutputs",t)}async relinquishOutput(t){return await this.api("relinquishOutput",t)}async getPublicKey(t){return await this.api("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.api("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.api("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.api("encrypt",t)}async decrypt(t){return await this.api("decrypt",t)}async createHmac(t){return await this.api("createHmac",t)}async verifyHmac(t){return await this.api("verifyHmac",t)}async createSignature(t){return await this.api("createSignature",t)}async verifySignature(t){return await this.api("verifySignature",t)}async acquireCertificate(t){return await this.api("acquireCertificate",t)}async listCertificates(t){return await this.api("listCertificates",t)}async proveCertificate(t){return await this.api("proveCertificate",t)}async relinquishCertificate(t){return await this.api("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.api("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.api("discoverByAttributes",t)}async isAuthenticated(t){return await this.api("isAuthenticated",t)}async waitForAuthentication(t){return await this.api("waitForAuthentication",t)}async getHeight(t){return await this.api("getHeight",t)}async getHeaderForHeight(t){return await this.api("getHeaderForHeight",t)}async getNetwork(t){return await this.api("getNetwork",t)}async getVersion(t){return await this.api("getVersion",t)}}class Yi{domain;constructor(t="*"){if("object"!=typeof window)throw new Error("The XDM substrate requires a global window object.");if(!window.hasOwnProperty("ReactNativeWebView"))throw new Error("The window object does not have a ReactNativeWebView property.");if("function"!=typeof window.ReactNativeWebView.postMessage)throw new Error("The window.ReactNativeWebView property does not seem to support postMessage calls.");this.domain=t}async invoke(t,e){return await new Promise(((i,r)=>{const s=Dt(xe(12)),n=t=>{const e=JSON.parse(t.data);if("CWI"===e.type&&e.id===s&&!0!==e.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",n),"error"===e.status){const t=new Hi(e.description,e.code);r(t)}else i(e.result)};window.addEventListener("message",n),window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:s,call:t,args:e}))}))}async createAction(t){return await this.invoke("createAction",t)}async signAction(t){return await this.invoke("signAction",t)}async abortAction(t){return await this.invoke("abortAction",t)}async listActions(t){return await this.invoke("listActions",t)}async internalizeAction(t){return await this.invoke("internalizeAction",t)}async listOutputs(t){return await this.invoke("listOutputs",t)}async relinquishOutput(t){return await this.invoke("relinquishOutput",t)}async getPublicKey(t){return await this.invoke("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.invoke("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.invoke("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.invoke("encrypt",t)}async decrypt(t){return await this.invoke("decrypt",t)}async createHmac(t){return await this.invoke("createHmac",t)}async verifyHmac(t){return await this.invoke("verifyHmac",t)}async createSignature(t){return await this.invoke("createSignature",t)}async verifySignature(t){return await this.invoke("verifySignature",t)}async acquireCertificate(t){return await this.invoke("acquireCertificate",t)}async listCertificates(t){return await this.invoke("listCertificates",t)}async proveCertificate(t){return await this.invoke("proveCertificate",t)}async relinquishCertificate(t){return await this.invoke("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.invoke("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.invoke("discoverByAttributes",t)}async isAuthenticated(t){return await this.invoke("isAuthenticated",t)}async waitForAuthentication(t){return await this.invoke("waitForAuthentication",t)}async getHeight(t){return await this.invoke("getHeight",t)}async getHeaderForHeight(t){return await this.invoke("getHeaderForHeight",t)}async getNetwork(t){return await this.invoke("getNetwork",t)}async getVersion(t){return await this.invoke("getVersion",t)}}class Zi{substrate;originator;constructor(t="auto",e){"Cicada"===t&&(t=new Wi(new Gi(e))),"window.CWI"===t&&(t=new Vi),"XDM"===t&&(t=new $i),"json-api"===t&&(t=new Ji(e)),"react-native"===t&&(t=new Yi(e)),"secure-json-api"===t&&(t=new Ji(e,"https://localhost:2121")),this.substrate=t,this.originator=e}async connectToSubstrate(){if("object"==typeof this.substrate)return;const t=async(t,e)=>{try{const i=t();let r;return r="number"==typeof e?await Promise.race([i.getVersion({}),new Promise(((t,i)=>setTimeout((()=>i(new Error("Timed out."))),e)))]):await i.getVersion({}),"object"!=typeof r||"string"!=typeof r.version?{success:!1}:{success:!0,sub:i}}catch{return{success:!1}}},e=[t((()=>new Vi)),t((()=>new Ji(this.originator,"https://localhost:2121"))),t((()=>new Ji(this.originator))),t((()=>new Yi(this.originator))),t((()=>new Wi(new Gi(this.originator))))],i=(await Promise.allSettled(e)).filter((t=>"fulfilled"===t.status&&t.value.success&&void 0!==t.value.sub)).map((t=>t.value.sub));if(i.length>0)return void(this.substrate=i[0]);const r=await t((()=>new $i),200);if(!r.success||void 0===r.sub)throw new Error("No wallet available over any communication substrate. Install a BSV wallet today!");this.substrate=r.sub}async createAction(t){return 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 Qi extends ji{keyring;decryptedFields;constructor(t,e,i,r,s,n,a,o,c){super(t,e,i,r,s,n,o),this.keyring=a,this.decryptedFields=c}static fromCertificate(t,e){return new Qi(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,e,t.signature)}async decryptFields(t,e,i,r){if(null==this.keyring||0===Object.keys(this.keyring).length)throw new Error("A keyring is required to decrypt certificate fields for the verifier.");try{const s={};for(const n in this.keyring){const{plaintext:a}=await t.decrypt({ciphertext:Ct(this.keyring[n],"base64"),...ji.getCertificateFieldEncryptionDetails(n,this.serialNumber),counterparty:this.subject,privileged:e,privilegedReason:i},r),o=new Qe(a).decrypt(Ct(this.fields[n],"base64"));s[n]=Lt(o)}return s}catch(t){throw new Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(t instanceof Error?t.message:t)}`)}}}class tr{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 er(t,e,i="self",r){const s=Ct(t,"base64"),n=s.slice(0,16),a=s.slice(16),{valid:o}=await e.verifyHmac({data:n,hmac:a,protocolID:[2,"server hmac"],keyID:Lt(n),counterparty:i},r);return o}async function ir(t,e="self",i){const r=xe(16),{hmac:s}=await t.createHmac({protocolID:[2,"server hmac"],keyID:Lt(r),data:r,counterparty:e},i);return Dt([...r,...s])}const rr=async(t,e,i,r)=>{const s=await t.listCertificates({certifiers:e.certifiers,types:Object.keys(e.types)},r);return await Promise.all(s.certificates.map((async s=>{const{keyringForVerifier:n}=await t.proveCertificate({certificate:s,fieldsToReveal:e.types[s.type],verifier:i},r);return new Qi(s.type,s.serialNumber,s.subject,s.certifier,s.revocationOutpoint,s.fields,n,s.signature)})))},sr=async(t,e,i,r)=>{if(null==e.certificates||0===e.certificates.length)throw new Error("No certificates were provided in the AuthMessage.");await Promise.all(e.certificates.map((async s=>{if(s.subject!==e.identityKey)throw new Error(`The subject of one of your certificates ("${s.subject}") is not the same as the request sender ("${e.identityKey}").`);const n=new Qi(s.type,s.serialNumber,s.subject,s.certifier,s.revocationOutpoint,s.fields,s.keyring,s.signature);if(!await n.verify())throw new Error(`The signature for the certificate with serial number ${n.serialNumber} is invalid!`);if(null!=i){const{certifiers:t,types:e}=i;if(!t.includes(n.certifier))throw new Error(`Certificate with serial number ${n.serialNumber} has an unrequested certifier: ${n.certifier}`);if(null==e[n.type])throw new Error(`Certificate with type ${n.type} was not requested`)}await n.decryptFields(t,void 0,void 0,r)})))},nr="0.1";class ar{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;constructor(t,e,i,r,s,n){this.wallet=t,this.originator=n,this.transport=e,this.certificatesToRequest=i??{certifiers:[],types:{}},this.transport.onData(this.handleIncomingMessage.bind(this)).catch((t=>{throw t})),this.sessionManager=null!=r?r:new tr,this.autoPersistLastSession=!1!==s}async toPeer(t,e,i){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof e&&(e=this.lastInteractedWithPeer);const r=await this.getAuthenticatedSession(e,i),s=Dt(xe(32)),{signature:n}=await this.wallet.createSignature({data:t,protocolID:[2,"auth message signature"],keyID:`${s} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey},this.originator),a={version:nr,messageType:"general",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,nonce:s,yourNonce:r.peerNonce,payload:t,signature:n};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),s=Dt(xe(32)),{signature:n}=await this.wallet.createSignature({data:Ct(JSON.stringify(t),"utf8"),protocolID:[2,"auth message signature"],keyID:`${s} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey},this.originator),a={version:nr,messageType:"certificateRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,nonce:s,initialNonce:r.sessionNonce,yourNonce:r.peerNonce,requestedCertificates:t,signature:n};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 ir(this.wallet,void 0,this.originator),r=Date.now();this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:i,peerIdentityKey:t,lastUpdate:r});const s={version:nr,messageType:"initialRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,initialNonce:i,requestedCertificates:this.certificatesToRequest};return await this.transport.send(s),await this.waitForInitialResponse(i,e)}async waitForInitialResponse(t,e=1e4){return await new Promise(((i,r)=>{const s=this.listenForInitialResponse(t,(t=>{clearTimeout(n),this.stopListeningForInitialResponses(s),i(t)})),n=setTimeout((()=>{this.stopListeningForInitialResponses(s),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!==nr)throw new Error(`Invalid or unsupported message auth version! Received: ${t.version}, expected: ${nr}`);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 ir(this.wallet,void 0,this.originator),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 rr(this.wallet,t.requestedCertificates,t.identityKey,this.originator));const{signature:s}=await this.wallet.createSignature({data:Ct(t.initialNonce+e,"base64"),protocolID:[2,"auth message signature"],keyID:`${t.initialNonce} ${e}`,counterparty:t.identityKey},this.originator),n={version:nr,messageType:"initialResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,initialNonce:e,yourNonce:t.initialNonce,certificates:r,requestedCertificates:this.certificatesToRequest,signature:s};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=t.identityKey),await this.transport.send(n)}async processInitialResponse(t){if(!await er(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Initial response nonce verification failed from peer: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Peer session not found for peer: ${t.identityKey}`);const i=Ct((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},this.originator);if(!r)throw new Error(`Unable to verify initial response signature for peer: ${t.identityKey}`);if(e.peerNonce=t.initialNonce,e.peerIdentityKey=t.identityKey,e.isAuthenticated=!0,e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),this.certificatesToRequest?.certifiers?.length>0&&t.certificates?.length>0&&(await sr(this.wallet,t,this.certificatesToRequest,this.originator),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 rr(this.wallet,t.requestedCertificates,t.identityKey,this.originator);await this.sendCertificateResponse(t.identityKey,e)}}async processCertificateRequest(t){if(!await er(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for certificate request message from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{valid:i}=await this.wallet.verifySignature({data:Ct(JSON.stringify(t.requestedCertificates),"utf8"),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:e.peerIdentityKey},this.originator);if(!i)throw new Error(`Invalid signature in certificate request message from ${e.peerIdentityKey}`);if(e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),null!=t.requestedCertificates&&Array.isArray(t.requestedCertificates.certifiers)&&t.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach((e=>{e(t.identityKey,t.requestedCertificates)}));else{const e=await rr(this.wallet,t.requestedCertificates,t.identityKey,this.originator);await this.sendCertificateResponse(t.identityKey,e)}}async sendCertificateResponse(t,e){const i=await this.getAuthenticatedSession(t),r=Dt(xe(32)),{signature:s}=await this.wallet.createSignature({data:Ct(JSON.stringify(e),"utf8"),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),n={version:nr,messageType:"certificateResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,certificates:e,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(n)}catch(t){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 er(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for certificate response from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{valid:i}=await this.wallet.verifySignature({data:Ct(JSON.stringify(t.certificates),"utf8"),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:t.identityKey},this.originator);if(!i)throw new Error(`Unable to verify certificate response signature for peer: ${t.identityKey}`);await sr(this.wallet,t,t.requestedCertificates,this.originator),this.onCertificatesReceivedCallbacks.forEach((e=>{e(t.identityKey,t.certificates??[])})),e.lastUpdate=Date.now(),this.sessionManager.updateSession(e)}async processGeneralMessage(t){if(!await er(t.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for general message from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{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},this.originator);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 or="undefined"!=typeof window?fetch.bind(window):fetch;class cr{onDataCallback;fetchClient;baseUrl;constructor(t,e=or){this.fetchClient=e,this.baseUrl=t}async send(t){if(null==this.onDataCallback)throw new Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==t.messageType)return await new Promise(((e,i)=>{(async()=>{try{const i=this.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||null==this.onDataCallback)throw new Error("HTTP server failed to authenticate");{const t=await r.json();this.onDataCallback(t)}"initialRequest"===t.messageType&&e()}catch(t){i(t)}})()}));{const e=this.deserializeRequestPayload(t.payload),i=`${this.baseUrl}${e.urlPostfix}`,r=e;if("object"!=typeof e.headers&&(r.headers={}),r.headers["x-bsv-auth-version"]=t.version,r.headers["x-bsv-auth-identity-key"]=t.identityKey,r.headers["x-bsv-auth-nonce"]=t.nonce,r.headers["x-bsv-auth-your-nonce"]=t.yourNonce,r.headers["x-bsv-auth-signature"]=Tt(t.signature),r.headers["x-bsv-auth-request-id"]=e.requestId,null!=r.body){const t=r.headers;if(null==t["content-type"])throw new Error("Content-Type header is required for requests with a body.");const e=String(t["content-type"]??"");e.includes("application/json")||e.includes("application/x-www-form-urlencoded")||e.includes("text/plain")?r.body=Lt(r.body):r.body=new Uint8Array(r.body)}const s=await this.fetchClient(i,{method:r.method,headers:r.headers,body:r.body});if(500===s.status&&null==s.headers.get("x-bsv-auth-request-id")&&null==s.headers.get("x-bsv-auth-requested-certificates")){const t=await s.json();throw new Error(`HTTP ${s.status} - ${JSON.stringify(t)}`)}const n=await s.arrayBuffer(),a=new Kt;null!=s.headers.get("x-bsv-auth-request-id")&&a.write(Ct(s.headers.get("x-bsv-auth-request-id"),"base64")),a.writeVarIntNum(s.status);const o=[];s.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=Ct(o[t][0],"utf8");a.writeVarIntNum(e.length),a.write(e);const i=Ct(o[t][1],"utf8");a.writeVarIntNum(i.length),a.write(i)}if(null!=n){const t=Array.from(new Uint8Array(n));a.writeVarIntNum(t.length),a.write(t)}else a.writeVarIntNum(-1);const c={version:s.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===s.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:s.headers.get("x-bsv-auth-identity-key"),nonce:s.headers.get("x-bsv-auth-nonce"),yourNonce:s.headers.get("x-bsv-auth-your-nonce"),requestedCertificates:JSON.parse(s.headers.get("x-bsv-auth-requested-certificates")),payload:a.toArray(),signature:Ct(s.headers.get("x-bsv-auth-signature"),"hex")};if(null==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 $t(t),i=Dt(e.read(32)),r=e.readVarIntNum();let s="GET";r>0&&(s=Lt(e.read(r)));const n=e.readVarIntNum();let a="";n>0&&(a=Lt(e.read(n)));const o=e.readVarIntNum();let c="";o>0&&(c=Lt(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=Lt(i),s=e.readVarIntNum(),n=e.read(s),a=Lt(n);h[r]=a}let u;const l=e.readVarIntNum();return l>0&&(u=e.read(l)),{urlPostfix:a+c,method:s,headers:h,body:u,requestId:i}}}class hr{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(t,e,i,r){this.wallet=t,this.requestedCertificates=e,this.sessionManager=i??new tr,this.originator=r}async fetch(t,e={}){if("number"==typeof e.retryCounter){if(e.retryCounter<=0)throw new Error("Request failed after maximum number of retries.");e.retryCounter--}const i=await new Promise((async(i,r)=>{try{const{method:s="GET",headers:n={},body:a}=e,o=new URL(t),c=o.origin;let h;if(void 0===this.peers[c]){const t=new cr(c);h={peer:new ar(this.wallet,t,this.requestedCertificates,this.sessionManager,void 0,this.originator),pendingCertificateRequests:[]},this.peers[c]=h,this.peers[c].peer.listenForCertificatesReceived(((t,e)=>{this.certificatesReceived.push(...e)})),this.peers[c].peer.listenForCertificatesRequested((async(t,e)=>{try{this.peers[c].pendingCertificateRequests.push(!0);const i=await rr(this.wallet,e,t,this.originator);await this.peers[c].peer.sendCertificateResponse(t,i)}finally{await new Promise((t=>setTimeout(t,500))),this.peers[c].pendingCertificateRequests.shift()}}))}else{if(!1===this.peers[c].supportsMutualAuth){try{const r=await this.handleFetchAndValidate(t,e,this.peers[c]);i(r)}catch(t){r(t)}return}h=this.peers[c]}const d=xe(32),u=Dt(d),l=await this.serializeRequest(s,n,a,o,d);this.callbacks[u]={resolve:i,reject:r};const f=h.peer.listenForGeneralMessages(((t,e)=>{const i=new $t(e);if(Dt(i.read(32))!==u)return;h.peer.stopListeningForGeneralMessages(f),this.peers[c].identityKey=t,this.peers[c].supportsMutualAuth=!0;const r=i.readVarIntNum(),s={},n=i.readVarIntNum();if(n>0)for(let t=0;t<n;t++){const t=i.readVarIntNum(),e=i.read(t),r=Lt(e),n=i.readVarIntNum(),a=i.read(n),o=Lt(a);s[r]=o}let a;s["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(s)});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 s=>{if(s.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(s.message.includes("HTTP server failed to authenticate"))try{const r=await this.handleFetchAndValidate(t,e,h);return void i(r)}catch(t){r(t)}else r(s)}))}catch(t){r(t)}}));return 402===i.status?await this.handlePaymentAndRetry(t,e,i):i}async sendCertificateRequest(t,e){const i=new URL(t).origin;let r;if(void 0!==this.peers[i])r={peer:this.peers[i].peer};else{const t=new cr(i);r={peer:new ar(this.wallet,t,this.requestedCertificates,this.sessionManager,this.originator)},this.peers[i]=r}return await new Promise((async(t,i)=>{const s=r.peer.listenForCertificatesReceived(((e,i)=>{r.peer.stopListeningForCertificatesReceived(s),this.certificatesReceived.push(...i),t(i)}));try{await r.peer.requestCertificates(e,r.identityKey)}catch(t){r.peer.stopListeningForCertificatesReceived(s),i(t)}}))}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(t,e,i,r,s){const n=new Kt;if(n.write(s),n.writeVarIntNum(t.length),n.write(Ct(t)),r.pathname.length>0){const t=Ct(r.pathname);n.writeVarIntNum(t.length),n.write(t)}else n.writeVarIntNum(-1);if(r.search.length>0){const t=Ct(r.search);n.writeVarIntNum(t.length),n.write(t)}else n.writeVarIntNum(-1);const a=[];for(let[t,i]of Object.entries(e))if(t=t.toLowerCase(),t.startsWith("x-bsv-")||"authorization"===t){if(t.startsWith("x-bsv-auth"))throw new Error("No BSV auth headers allowed here!");a.push([t,i])}else{if(!t.startsWith("content-type"))throw new Error("Unsupported header in the simplified fetch implementation. Only content-type, authorization, and x-bsv-* headers are supported.");i=i.split(";")[0].trim(),a.push([t,i])}a.sort((([t],[e])=>t.localeCompare(e))),n.writeVarIntNum(a.length);for(let t=0;t<a.length;t++){const e=Ct(a[t][0],"utf8");n.writeVarIntNum(e.length),n.write(e);const i=Ct(a[t][1],"utf8");n.writeVarIntNum(i.length),n.write(i)}if(["POST","PUT","PATCH","DELETE"].includes(t.toUpperCase())&&void 0===i){const t=a.find((([t])=>"content-type"===t));i=t&&t[1].includes("application/json")?"{}":""}if(i){const t=await this.normalizeBodyToNumberArray(i);n.writeVarIntNum(t.length),n.write(t)}else n.writeVarIntNum(-1);return n}async handleFetchAndValidate(t,e,i){const r=await fetch(t,e);if(r.headers.forEach((t=>{if(t.toLocaleLowerCase().startsWith("x-bsv"))throw new Error("The server is trying to claim it has been authenticated when it has not!")})),r.ok)return i.supportsMutualAuth=!1,r;throw new Error(`Request failed with status: ${r.status}`)}async handlePaymentAndRetry(t,e={},i){const r=i.headers.get("x-bsv-payment-version");if(!r||"1.0"!==r)throw new Error(`Unsupported x-bsv-payment-version response header. Client version: 1.0, Server version: ${r}`);const s=i.headers.get("x-bsv-payment-satoshis-required");if(!s)throw new Error("Missing x-bsv-payment-satoshis-required response header.");const n=parseInt(s);if(isNaN(n)||n<=0)throw new Error("Invalid x-bsv-payment-satoshis-required response header value.");const a=i.headers.get("x-bsv-auth-identity-key");if("string"!=typeof a)throw new Error("Missing x-bsv-auth-identity-key response header.");const o=i.headers.get("x-bsv-payment-derivation-prefix");if("string"!=typeof o||o.length<1)throw new Error("Missing x-bsv-payment-derivation-prefix response header.");const c=await ir(this.wallet,void 0,this.originator),{publicKey:h}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${o} ${c}`,counterparty:a},this.originator),d=(new bi).lock(_e.fromString(h).toAddress()).toHex(),{tx:u}=await this.wallet.createAction({description:`Payment for request to ${new URL(t).origin}`,outputs:[{satoshis:n,lockingScript:d,customInstructions:JSON.stringify({derivationPrefix:o,derivationSuffix:c,payee:a}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}},this.originator);return e.headers=e.headers||{},e.headers["x-bsv-payment"]=JSON.stringify({derivationPrefix:o,derivationSuffix:c,transaction:Dt(u)}),e.retryCounter??=3,this.fetch(t,e)}async normalizeBodyToNumberArray(t){if(null==t)return[];if("object"==typeof t)return Ct(JSON.stringify(t,"utf8"));if(Array.isArray(t)&&t.every((t=>"number"==typeof t)))return t;if("string"==typeof t)return Ct(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 Ct(i,"utf8")}if(t instanceof URLSearchParams)return Ct(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 dr{pushDrop;static decode(t){const e=yi.decode(t);if(e.fields.length<4)throw new Error("Invalid SHIP/SLAP advertisement!");const i=Lt(e.fields[0]);if("SHIP"!==i&&"SLAP"!==i)throw new Error("Invalid protocol type!");return{protocol:i,identityKey:Tt(e.fields[1]),domain:Lt(e.fields[2]),topicOrService:Lt(e.fields[3])}}constructor(t){this.pushDrop=new yi(t)}async lock(t,e,i){const{publicKey:r}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([Ct(t,"utf8"),Ct(r,"hex"),Ct(e,"utf8"),Ct(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 ur="undefined"!=typeof window?fetch.bind(window):fetch,lr=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],fr=["https://testnet-users.bapp.dev"];class pr{fetchClient;allowHTTP;constructor(t=ur,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="undefined"!=typeof AbortController?new AbortController:void 0,s=setTimeout((()=>{try{r?.abort()}catch{}}),i);try{const i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:e.service,query:e.query}),signal:r?.signal},s=await this.fetchClient(`${t}/lookup`,i);if(!s.ok)throw new Error(`Failed to facilitate lookup (HTTP ${s.status})`);return await s.json()}catch(t){if("AbortError"===t?.name)throw new Error("Request timed out");throw t}finally{clearTimeout(s)}}}class br{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(t={}){this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new pr(void 0,"local"===this.networkPreset),this.slapTrackers=t.slapTrackers??("mainnet"===this.networkPreset?lr:fr),this.hostOverrides=t.hostOverrides??{},this.additionalHosts=t.additionalHosts??{},this.hostsTtlMs=t.cache?.hostsTtlMs??3e5,this.hostsMaxEntries=t.cache?.hostsMaxEntries??128,this.txMemoTtlMs=t.cache?.txMemoTtlMs??6e5,this.hostsCache=new Map,this.hostsInFlight=new Map,this.txMemo=new Map}async query(t,e){let i=[];if(i="ls_slap"===t.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[t.service]?this.hostOverrides[t.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.getCompetentHostsCached(t.service),this.additionalHosts[t.service]?.length>0){const e=this.additionalHosts[t.service],r=new Set(i);for(const t of e)r.has(t)||i.push(t)}if(i.length<1)throw new Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${t.service}`);const r=await Promise.allSettled(i.map((async i=>await this.facilitator.lookup(i,t,e)))),s=new Map;for(const t of r){if("fulfilled"!==t.status)continue;const e=t.value;if("output-list"===e?.type&&Array.isArray(e.outputs))for(const t of e.outputs){const e="object"!=typeof(n=t.beef)?"":n.join(",");let i=this.txMemo.get(e);const r=Date.now();if("object"!=typeof i||null===i||i.expiresAt<=r)try{i={txId:Li.fromBEEF(t.beef).id("hex"),expiresAt:r+this.txMemoTtlMs},this.txMemo.size>4096&&this.evictOldest(this.txMemo),this.txMemo.set(e,i)}catch{continue}const a=`${i.txId}.${t.outputIndex}`;s.set(a,t)}}var n;return{type:"output-list",outputs:Array.from(s.values())}}async getCompetentHostsCached(t){const e=Date.now(),i=this.hostsCache.get(t);if("object"==typeof i&&i.expiresAt>e)return i.hosts.slice();if("object"==typeof i&&i.expiresAt<=e)return this.hostsInFlight.has(t)||this.hostsInFlight.set(t,this.refreshHosts(t).finally((()=>{this.hostsInFlight.delete(t)}))),i.hosts.slice();if(this.hostsInFlight.has(t))try{const e=await this.hostsInFlight.get(t);if("object"!=typeof e)throw new Error("Hosts is not defined.");return e.slice()}catch{}const r=this.refreshHosts(t).finally((()=>{this.hostsInFlight.delete(t)}));return this.hostsInFlight.set(t,r),(await r).slice()}async refreshHosts(t){const e=await this.findCompetentHosts(t),i=Date.now()+this.hostsTtlMs;if(!this.hostsCache.has(t)&&this.hostsCache.size>=this.hostsMaxEntries){const t=this.hostsCache.keys().next().value;void 0!==t&&this.hostsCache.delete(t)}return this.hostsCache.set(t,{hosts:e,expiresAt:i}),e}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)continue;const i=e.value;if("output-list"===i.type)for(const e of i.outputs)try{const i=Li.fromBEEF(e.beef),s=i.outputs[e.outputIndex]?.lockingScript;if("object"!=typeof s||null===s)continue;const n=dr.decode(s);if(n.topicOrService!==t||"SLAP"!==n.protocol)continue;"string"==typeof n.domain&&n.domain.length>0&&r.add(n.domain)}catch{continue}}return[...r]}evictOldest(t){const e=t.keys().next().value;void 0!==e&&t.delete(e)}}class gr{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 Kt;t.writeVarIntNum(e.beef.length),t.write(e.beef),t.write(e.offChainValues),r=new Uint8Array(t.toArray())}else r=new Uint8Array(e.beef);const s=await fetch(`${t}/submit`,{method:"POST",headers:i,body:r});if(s.ok)return await s.json();throw new Error("Failed to facilitate broadcast")}}class yr{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 gr(void 0,"local"===this.networkPreset),this.resolver=e.resolver??new br({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 s=Object.entries(r).map((async([t,r])=>{try{const s=await this.facilitator.send(t,{beef:e,offChainValues:i,topics:[...r]});if(null==s||0===Object.keys(s).length)throw new Error("Steak has no topics.");return{host:t,success:!0,steak:s}}catch(e){return console.error(e),{host:t,success:!1,error:e}}})),n=(await Promise.all(s)).filter((t=>t.success));if(0===n.length)return{status:"error",code:"ERR_ALL_HOSTS_REJECTED",description:`All ${this.networkPreset} topical hosts have rejected the transaction.`};const a={};for(const t of n){const e=t.host,i=t.steak,r=new Set;for(const[t,e]of Object.entries(i)){const i=e.outputsToAdmit,s=e.coinsToRetain,n=e.coinsRemoved;(i?.length>0||s?.length>0||n?.length>0)&&r.add(t)}a[e]=r}let o,c,h,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 ${n.length} Overlay Services ${1===n.length?"host":"hosts"}.`})}checkAcknowledgmentFromAllHosts(t,e,i){for(const r of Object.values(t))if("all"===i){for(const t of e)if(!r.has(t))return!1}else if("any"===i){let t=!1;for(const i of e)if(r.has(i)){t=!0;break}if(!t)return!1}return!0}checkAcknowledgmentFromAnyHost(t,e,i){if("all"===i){for(const i of Object.values(t)){let t=!0;for(const r of e)if(!i.has(r)){t=!1;break}if(t)return!0}return!1}for(const i of Object.values(t))for(const t of e)if(i.has(t))return!0;return!1}checkAcknowledgmentFromSpecificHosts(t,e){for(const[i,r]of Object.entries(e)){const e=t[i];if(null==e)return!1;let s,n;if("all"===r||"any"===r)n=r,s=this.topics;else{if(!Array.isArray(r))continue;s=r,n="all"}if("all"===n){for(const t of s)if(!e.has(t))return!1}else if("any"===n){let t=!1;for(const i of s)if(e.has(i)){t=!0;break}if(!t)return!1}}return!0}async findInterestedHosts(){if("local"===this.networkPreset){const t=new Set;for(let e=0;e<this.topics.length;e++)t.add(this.topics[e]);return{"http://localhost:8080":t}}const t={},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=Li.fromBEEF(i.beef).outputs[i.outputIndex].lockingScript,r=dr.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 mr=Object.create(null);mr.open="0",mr.close="1",mr.ping="2",mr.pong="3",mr.message="4",mr.upgrade="5",mr.noop="6";const wr=Object.create(null);Object.keys(mr).forEach((t=>{wr[mr[t]]=t}));const Ir={type:"error",data:"parser error"},vr="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),kr="function"==typeof ArrayBuffer,Sr=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,Er=({type:t,data:e},i,r)=>vr&&e instanceof Blob?i?r(e):_r(e,r):kr&&(e instanceof ArrayBuffer||Sr(e))?i?r(e):_r(new Blob([e]),r):r(mr[t]+(e||"")),_r=(t,e)=>{const i=new FileReader;return i.onload=function(){const t=i.result.split(",")[1];e("b"+(t||""))},i.readAsDataURL(t)};function Pr(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let Or;const xr="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)xr["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const Nr="function"==typeof ArrayBuffer,Ar=(t,e)=>{if("string"!=typeof t)return{type:"message",data:Cr(t,e)};const i=t.charAt(0);return"b"===i?{type:"message",data:Tr(t.substring(1),e)}:wr[i]?t.length>1?{type:wr[i],data:t.substring(1)}:{type:wr[i]}:Ir},Tr=(t,e)=>{if(Nr){const i=(t=>{let e,i,r,s,n,a=.75*t.length,o=t.length,c=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);const h=new ArrayBuffer(a),d=new Uint8Array(h);for(e=0;e<o;e+=4)i=xr[t.charCodeAt(e)],r=xr[t.charCodeAt(e+1)],s=xr[t.charCodeAt(e+2)],n=xr[t.charCodeAt(e+3)],d[c++]=i<<2|r>>4,d[c++]=(15&r)<<4|s>>2,d[c++]=(3&s)<<6|63&n;return h})(t);return Cr(i,e)}return{base64:!0,data:t}},Cr=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,Rr=String.fromCharCode(30);let Br;function Lr(t){return t.reduce(((t,e)=>t+e.length),0)}function Mr(t,e){if(t[0].length===e)return t.shift();const i=new Uint8Array(e);let r=0;for(let s=0;s<e;s++)i[s]=t[0][r++],r===t[0].length&&(t.shift(),r=0);return t.length&&r<t[0].length&&(t[0]=t[0].slice(r)),i}function Dr(t){if(t)return function(t){for(var e in Dr.prototype)t[e]=Dr.prototype[e];return t}(t)}Dr.prototype.on=Dr.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Dr.prototype.once=function(t,e){function i(){this.off(t,i),e.apply(this,arguments)}return i.fn=e,this.on(t,i),this},Dr.prototype.off=Dr.prototype.removeListener=Dr.prototype.removeAllListeners=Dr.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var i,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var s=0;s<r.length;s++)if((i=r[s])===e||i.fn===e){r.splice(s,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},Dr.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),i=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(i){r=0;for(var s=(i=i.slice(0)).length;r<s;++r)i[r].apply(this,e)}return this},Dr.prototype.emitReserved=Dr.prototype.emit,Dr.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Dr.prototype.hasListeners=function(t){return!!this.listeners(t).length};const Fr="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),Vr="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Hr(t,...e){return e.reduce(((e,i)=>(t.hasOwnProperty(i)&&(e[i]=t[i]),e)),{})}const qr=Vr.setTimeout,Ur=Vr.clearTimeout;function Kr(t,e){e.useNativeTimers?(t.setTimeoutFn=qr.bind(Vr),t.clearTimeoutFn=Ur.bind(Vr)):(t.setTimeoutFn=Vr.setTimeout.bind(Vr),t.clearTimeoutFn=Vr.clearTimeout.bind(Vr))}function $r(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class jr extends Error{constructor(t,e,i){super(t),this.description=e,this.context=i,this.type="TransportError"}}class zr extends Dr{constructor(t){super(),this.writable=!1,Kr(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 jr(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=Ar(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 Wr extends zr{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(Rr),r=[];for(let t=0;t<i.length;t++){const s=Ar(i[t],e);if(r.push(s),"error"===s.type)break}return r})(t,this.socket.binaryType).forEach((t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)})),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const i=t.length,r=new Array(i);let s=0;t.forEach(((t,n)=>{Er(t,!1,(t=>{r[n]=t,++s===i&&e(r.join(Rr))}))}))})(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]=$r()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let Gr=!1;try{Gr="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const Xr=Gr;function Jr(){}class Yr extends Wr{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 Zr extends Dr{constructor(t,e,i){super(),this.createRequest=t,Kr(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=Hr(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=Zr.requestsCount++,Zr.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=Jr,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Zr.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 Qr(){for(let t in Zr.requests)Zr.requests.hasOwnProperty(t)&&Zr.requests[t].abort()}Zr.requestsCount=0,Zr.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Qr):"function"==typeof addEventListener&&addEventListener("onpagehide"in Vr?"pagehide":"unload",Qr,!1));const ts=function(){const t=es({xdomain:!1});return t&&null!==t.responseType}();function es(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||Xr))return new XMLHttpRequest}catch(t){}if(!e)try{return new(Vr[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const is="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class rs extends zr{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,i=is?{}:Hr(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;Er(i,this.supportsBinary,(t=>{try{this.doWrite(i,t)}catch(t){}r&&Fr((()=>{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]=$r()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const ss=Vr.WebSocket||Vr.MozWebSocket,ns={websocket:class extends rs{createSocket(t,e,i){return is?new ss(t,e,i):e?new ss(t,e):new ss(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends zr{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){Br||(Br=new TextDecoder);const i=[];let r=0,s=-1,n=!1;return new TransformStream({transform(a,o){for(i.push(a);;){if(0===r){if(Lr(i)<1)break;const t=Mr(i,1);n=!(128&~t[0]),s=127&t[0],r=s<126?3:126===s?1:2}else if(1===r){if(Lr(i)<2)break;const t=Mr(i,2);s=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),r=3}else if(2===r){if(Lr(i)<8)break;const t=Mr(i,8),e=new DataView(t.buffer,t.byteOffset,t.length),n=e.getUint32(0);if(n>Math.pow(2,21)-1){o.enqueue(Ir);break}s=n*Math.pow(2,32)+e.getUint32(4),r=3}else{if(Lr(i)<s)break;const t=Mr(i,s);o.enqueue(Ar(n?t:Br.decode(t),e)),r=0}if(0===s||s>t){o.enqueue(Ir);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=t.readable.pipeThrough(e).getReader(),r=new TransformStream({transform(t,e){!function(t,e){vr&&t.data instanceof Blob?t.data.arrayBuffer().then(Pr).then(e):kr&&(t.data instanceof ArrayBuffer||Sr(t.data))?e(Pr(t.data)):Er(t,!1,(t=>{Or||(Or=new TextEncoder),e(Or.encode(t))}))}(t,(i=>{const r=i.length;let s;if(r<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,r);else if(r<65536){s=new Uint8Array(3);const t=new DataView(s.buffer);t.setUint8(0,126),t.setUint16(1,r)}else{s=new Uint8Array(9);const t=new DataView(s.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(r))}t.data&&"string"!=typeof t.data&&(s[0]|=128),e.enqueue(s),e.enqueue(i)}))}});r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const s=()=>{i.read().then((({done:t,value:e})=>{t||(this.onPacket(e),s())})).catch((t=>{}))};s();const n={type:"open"};this.query.sid&&(n.data=`{"sid":"${this.query.sid}"}`),this._writer.write(n).then((()=>this.onOpen()))}))}))}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const i=t[e],r=e===t.length-1;this._writer.write(i).then((()=>{r&&Fr((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends Yr{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=ts&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Zr(es,this.uri(),t)}}},as=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,os=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function cs(t){if(t.length>8e3)throw"URI too long";const e=t,i=t.indexOf("["),r=t.indexOf("]");-1!=i&&-1!=r&&(t=t.substring(0,i)+t.substring(i,r).replace(/:/g,";")+t.substring(r,t.length));let s=as.exec(t||""),n={},a=14;for(;a--;)n[os[a]]=s[a]||"";return-1!=i&&-1!=r&&(n.source=e,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=function(t,e){const i=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||i.splice(0,1),"/"==e.slice(-1)&&i.splice(i.length-1,1),i}(0,n.path),n.queryKey=function(t,e){const i={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,r){e&&(i[e]=r)})),i}(0,n.query),n}const hs="function"==typeof addEventListener&&"function"==typeof removeEventListener,ds=[];hs&&addEventListener("offline",(()=>{ds.forEach((t=>t()))}),!1);class us extends Dr{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=cs(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=cs(e.host).host);Kr(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)),hs&&(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"})},ds.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&&us.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",us.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,s=t.length;r<s;r++)e=t.charCodeAt(r),e<128?i+=1:e<2048?i+=2:e<55296||e>=57344?i+=3:(r++,i+=4);return i}(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,Fr((()=>{this._onClose("ping timeout")}),this.setTimeoutFn)),t}write(t,e,i){return this._sendPacket("message",t,e,i),this}send(t,e,i){return this._sendPacket("message",t,e,i),this}_sendPacket(t,e,i,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof i&&(r=i,i=null),"closing"===this.readyState||"closed"===this.readyState)return;(i=i||{}).compress=!1!==i.compress;const s={type:t,data:e,options:i};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},i=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?i():t()})):this.upgrading?i():t()),this}_onError(t){if(us.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(),hs&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=ds.indexOf(this._offlineEventListener);-1!==t&&ds.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}us.protocol=4;class ls extends us{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;us.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;us.priorWebsocketSuccess="websocket"===e.name,this.transport.pause((()=>{i||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())}))}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}})))};function s(){i||(i=!0,h(),e.close(),e=null)}const n=t=>{const i=new Error("probe error: "+t);i.transport=e.name,s(),this.emitReserved("upgradeError",i)};function a(){n("transport closed")}function o(){n("socket closed")}function c(t){e&&t.name!==e.name&&s()}const h=()=>{e.removeListener("open",r),e.removeListener("error",n),e.removeListener("close",a),this.off("close",o),this.off("upgrading",c)};e.once("open",r),e.once("error",n),e.once("close",a),this.once("close",o),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn((()=>{i||e.open()}),200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let i=0;i<t.length;i++)~this.transports.indexOf(t[i])&&e.push(t[i]);return e}}class fs extends ls{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=>ns[t])).filter((t=>!!t))),super(t,i)}}const ps="function"==typeof ArrayBuffer,bs=Object.prototype.toString,gs="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===bs.call(Blob),ys="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===bs.call(File);function ms(t){return ps&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||gs&&t instanceof Blob||ys&&t instanceof File}function ws(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,i=t.length;e<i;e++)if(ws(t[e]))return!0;return!1}if(ms(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return ws(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&ws(t[e]))return!0;return!1}function Is(t){const e=[],i=t.data,r=t;return r.data=vs(i,e),r.attachments=e.length,{packet:r,buffers:e}}function vs(t,e){if(!t)return t;if(ms(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]=vs(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]=vs(t[r],e));return i}return t}function ks(t,e){return t.data=Ss(t.data,e),delete t.attachments,t}function Ss(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]=Ss(t[i],e);else if("object"==typeof t)for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=Ss(t[i],e));return t}const Es=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],_s=5;var Ps;!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"}(Ps||(Ps={}));class Os{constructor(t){this.replacer=t}encode(t){return t.type!==Ps.EVENT&&t.type!==Ps.ACK||!ws(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===Ps.EVENT?Ps.BINARY_EVENT:Ps.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==Ps.BINARY_EVENT&&t.type!==Ps.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=Is(t),i=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(i),r}}function xs(t){return"[object Object]"===Object.prototype.toString.call(t)}class Ns extends Dr{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===Ps.BINARY_EVENT;i||e.type===Ps.BINARY_ACK?(e.type=i?Ps.EVENT:Ps.ACK,this.reconstructor=new As(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!ms(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===Ps[i.type])throw new Error("unknown packet type "+i.type);if(i.type===Ps.BINARY_EVENT||i.type===Ps.BINARY_ACK){const r=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const s=t.substring(r,e);if(s!=Number(s)||"-"!==t.charAt(e))throw new Error("Illegal attachments");i.attachments=Number(s)}if("/"===t.charAt(e+1)){const r=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);i.nsp=t.substring(r,e)}else i.nsp="/";const r=t.charAt(e+1);if(""!==r&&Number(r)==r){const r=e+1;for(;++e;){const i=t.charAt(e);if(null==i||Number(i)!=i){--e;break}if(e===t.length)break}i.id=Number(t.substring(r,e+1))}if(t.charAt(++e)){const r=this.tryParse(t.substr(e));if(!Ns.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 Ps.CONNECT:return xs(e);case Ps.DISCONNECT:return void 0===e;case Ps.CONNECT_ERROR:return"string"==typeof e||xs(e);case Ps.EVENT:case Ps.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===Es.indexOf(e[0]));case Ps.ACK:case Ps.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class As{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=ks(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function Ts(t,e,i){return t.on(e,i),function(){t.off(e,i)}}const Cs=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Rs extends Dr{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=[Ts(t,"open",this.onopen.bind(this)),Ts(t,"packet",this.onpacket.bind(this)),Ts(t,"error",this.onerror.bind(this)),Ts(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var i,r,s;if(Cs.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const n={type:Ps.EVENT,data:e,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,i=e.pop();this._registerAckCallback(t,i),n.id=t}const a=null===(r=null===(i=this.io.engine)||void 0===i?void 0:i.transport)||void 0===r?void 0:r.writable,o=this.connected&&!(null===(s=this.io.engine)||void 0===s?void 0:s._hasPingExpired());return this.flags.volatile&&!a||(o?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(t,e){var i;const r=null!==(i=this.flags.timeout)&&void 0!==i?i:this._opts.ackTimeout;if(void 0===r)return void(this.acks[t]=e);const s=this.io.setTimeoutFn((()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))}),r),n=(...t)=>{this.io.clearTimeoutFn(s),e.apply(this,t)};n.withError=!0,this.acks[t]=n}emitWithAck(t,...e){return new Promise(((i,r)=>{const s=(t,e)=>t?r(t):i(e);s.withError=!0,e.push(s),this.emit(t,...e)}))}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const i={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push(((t,...r)=>{if(i===this._queue[0])return null!==t?i.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...r)),i.pending=!1,this._drainQueue()})),this._queue.push(i),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth((t=>{this._sendConnectPacket(t)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:Ps.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 Ps.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 Ps.EVENT:case Ps.BINARY_EVENT:this.onevent(t);break;case Ps.ACK:case Ps.BINARY_ACK:this.onack(t);break;case Ps.DISCONNECT:this.ondisconnect();break;case Ps.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:Ps.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:Ps.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 Bs(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}Bs.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)},Bs.prototype.reset=function(){this.attempts=0},Bs.prototype.setMin=function(t){this.ms=t},Bs.prototype.setMax=function(t){this.max=t},Bs.prototype.setJitter=function(t){this.jitter=t};class Ls extends Dr{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,Kr(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 Bs({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const s=e.parser||i;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new fs(this.uri,this.opts);const e=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const r=Ts(e,"open",(function(){i.onopen(),t&&t()})),s=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},n=Ts(e,"error",s);if(!1!==this._timeout){const t=this._timeout,i=this.setTimeoutFn((()=>{r(),s(new Error("timeout")),e.close()}),t);this.opts.autoUnref&&i.unref(),this.subs.push((()=>{this.clearTimeoutFn(i)}))}return this.subs.push(r),this.subs.push(n),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Ts(t,"ping",this.onping.bind(this)),Ts(t,"data",this.ondata.bind(this)),Ts(t,"error",this.onerror.bind(this)),Ts(t,"close",this.onclose.bind(this)),Ts(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){Fr((()=>{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 Rs(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 Ms={};function Ds(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=cs(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const s=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+s+":"+r.port+e,r.href=r.protocol+"://"+s+(i&&i.port===r.port?"":":"+r.port),r}(t,(e=e||{}).path||"/socket.io"),r=i.source,s=i.id,n=i.path,a=Ms[s]&&n in Ms[s].nsps;let o;return e.forceNew||e["force new connection"]||!1===e.multiplex||a?o=new Ls(r,e):(Ms[s]||(Ms[s]=new Ls(r,e)),o=Ms[s]),i.query&&!e.query&&(e.query=i.queryKey),o.socket(i.path,e)}Object.assign(Ds,{Manager:Ls,Socket:Rs,io:Ds,connect:Ds});class Fs{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 Vs{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 Ct(JSON.stringify(i),"utf8")}decodeEventPayload(t){try{const e=Lt(t);return JSON.parse(e)}catch{return{eventName:"_unknown",data:void 0}}}}let Hs=!1;function qs(...t){Hs&&console.log(...t)}function Us(...t){Hs&&console.warn(...t)}function Ks(...t){console.error(...t)}class $s{host;authFetch;walletClient;socket;myIdentityKey;joinedRooms=new Set;lookupResolver;networkPreset;initialized=!1;originator;constructor(t={}){const{host:e,walletClient:i,enableLogging:r=!1,networkPreset:s="mainnet",originator:n}=t,a="testnet"===this.networkPreset?"https://staging-messagebox.babbage.systems":"https://messagebox.babbage.systems";this.host=e?.trim()??a,this.originator=n,this.walletClient=i??new Zi("auto",n),this.authFetch=new hr(this.walletClient,void 0,void 0,n),this.networkPreset=s,this.lookupResolver=new br({networkPreset:s}),r&&(Hs=!0)}async init(t=this.host){const e=t?.trim();if(""===e)throw new Error("Cannot anoint host: No valid host provided");if(e!==this.host&&(this.initialized=!1,this.host=e),this.initialized)return;const i=await this.getIdentityKey(),[r]=await this.queryAdvertisements(i,e);if(null==r||""===r?.host?.trim()||r?.host!==e){qs("[MB CLIENT] Anointing host:",e);try{const{txid:t}=await this.anointHost(e);if(null==t||""===t.trim())throw new Error("Failed to anoint host: No transaction ID returned")}catch(t){qs("[MB CLIENT] Failed to anoint host, continuing with default functionality:",t)}}this.initialized=!0}async assertInitialized(){this.initialized&&null!=this.host&&""!==this.host.trim()||await this.init()}getJoinedRooms(){return this.joinedRooms}async getIdentityKey(){if(null!=this.myIdentityKey&&""!==this.myIdentityKey.trim())return this.myIdentityKey;qs("[MB CLIENT] Fetching identity key...");try{const t=await this.walletClient.getPublicKey({identityKey:!0},this.originator);return this.myIdentityKey=t.publicKey,qs(`[MB CLIENT] Identity key fetched: ${this.myIdentityKey}`),this.myIdentityKey}catch(t){throw Ks("[MB CLIENT ERROR] Failed to fetch identity key:",t),new Error("Identity key retrieval failed")}}get testSocket(){return this.socket}async initializeConnection(t){if(qs("[MB CLIENT] initializeConnection() STARTED"),null!=this.myIdentityKey&&""!==this.myIdentityKey.trim()||await this.getIdentityKey(),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw Ks("[MB CLIENT ERROR] Identity key is still missing after retrieval!"),new Error("Identity key is missing");if(qs("[MB CLIENT] Setting up WebSocket connection..."),null==this.socket){const e=t??this.host;if("string"!=typeof e||""===e.trim())throw new Error("Cannot initialize WebSocket: No valid host provided");this.socket=function(t,e){const i=Ds(t,e.managerOptions),r=new Fs(i),s=new ar(e.wallet,r,e.requestedCertificates,e.sessionManager,void 0,e.originator);return new Vs(i,s)}(e,{wallet:this.walletClient,originator:this.originator});let i=!1,r=!1;this.socket.on("connect",(()=>{qs("[MB CLIENT] Connected to WebSocket."),i||(qs("[MB CLIENT] Sending authentication data:",this.myIdentityKey),null==this.myIdentityKey||""===this.myIdentityKey.trim()?Ks("[MB CLIENT ERROR] Cannot send authentication: Identity key is missing!"):(this.socket?.emit("authenticated",{identityKey:this.myIdentityKey}),i=!0))})),this.socket.on("authenticationSuccess",(t=>{qs(`[MB CLIENT] WebSocket authentication successful: ${JSON.stringify(t)}`),r=!0})),this.socket.on("authenticationFailed",(t=>{Ks(`[MB CLIENT ERROR] WebSocket authentication failed: ${JSON.stringify(t)}`),r=!1})),this.socket.on("disconnect",(()=>{qs("[MB CLIENT] Disconnected from MessageBox server"),this.socket=void 0,i=!1,r=!1})),this.socket.on("error",(t=>{Ks("[MB CLIENT ERROR] WebSocket error:",t)})),await new Promise(((t,e)=>{setTimeout((()=>{r?(qs("[MB CLIENT] WebSocket fully authenticated and ready!"),t()):e(new Error("[MB CLIENT ERROR] WebSocket authentication timed out!"))}),5e3)}))}}async resolveHostForRecipient(t){const e=await this.queryAdvertisements(t,void 0);return 0===e.length?(Us(`[MB CLIENT] No advertisements for ${t}, using default host ${this.host}`),this.host):e[0].host}async queryAdvertisements(t,e){const i=[];try{const r={identityKey:t??await this.getIdentityKey()};null!=e&&""!==e.trim()&&(r.host=e);const s=await this.lookupResolver.query({service:"ls_messagebox",query:r});if("output-list"!==s.type)throw new Error(`Unexpected result type: ${String(s.type)}`);for(const t of s.outputs)try{const e=Li.fromBEEF(t.beef),r=e.outputs[t.outputIndex].lockingScript,s=yi.decode(r),[,n]=s.fields;if(null==n||0===n.length)throw new Error("Empty host field");i.push({host:Lt(n),txid:e.id("hex"),outputIndex:t.outputIndex,lockingScript:r,beef:t.beef})}catch{}}catch(t){Ks("[MB CLIENT ERROR] _queryAdvertisements failed:",t)}return i}async joinRoom(t,e){if(qs(`[MB CLIENT] Attempting to join WebSocket room: ${t}`),null==this.socket&&(qs("[MB CLIENT] No WebSocket connection. Initializing..."),await this.initializeConnection(e)),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw new Error("[MB CLIENT ERROR] Identity key is not defined");const i=`${this.myIdentityKey??""}-${t}`;if(this.joinedRooms.has(i))qs(`[MB CLIENT] Already joined WebSocket room: ${i}`);else try{qs(`[MB CLIENT] Joining WebSocket room: ${i}`),await(this.socket?.emit("joinRoom",i)),this.joinedRooms.add(i),qs(`[MB CLIENT] Successfully joined room: ${i}`)}catch(t){Ks(`[MB CLIENT ERROR] Failed to join WebSocket room: ${i}`,t)}}async listenForLiveMessages({onMessage:t,messageBox:e,overrideHost:i}){if(qs(`[MB CLIENT] Setting up listener for WebSocket room: ${e}`),null==this.socket&&(qs("[MB CLIENT] No WebSocket connection. Initializing..."),await this.initializeConnection(i)),await this.joinRoom(e,this.originator),null==this.myIdentityKey||""===this.myIdentityKey.trim())throw new Error("[MB CLIENT ERROR] Identity key is missing. Cannot construct room ID.");const r=`${this.myIdentityKey}-${e}`;qs(`[MB CLIENT] Listening for messages in room: ${r}`),this.socket?.on(`sendMessage-${r}`,(e=>{(async()=>{qs(`[MB CLIENT] Received message in room ${r}:`,e);try{let t=e.body;if("string"==typeof t)try{t=JSON.parse(t)}catch{}if(null!=t&&"object"==typeof t&&"string"==typeof t.encryptedMessage){qs(`[MB CLIENT] Decrypting message from ${String(e.sender)}...`);const i=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:e.sender,ciphertext:Ct(t.encryptedMessage,"base64")},this.originator);e.body=Lt(i.plaintext)}else qs("[MB CLIENT] Message is not encrypted."),e.body="string"==typeof t?t:(()=>{try{return JSON.stringify(t)}catch{return"[Error: Unstringifiable message]"}})()}catch(t){Ks("[MB CLIENT ERROR] Failed to parse or decrypt live message:",t),e.body="[Error: Failed to decrypt or parse message]"}t(e)})()}))}async sendLiveMessage({recipient:t,messageBox:e,body:i,messageId:r,skipEncryption:s,checkPermissions:n},a){if(null==t||""===t.trim())throw new Error("[MB CLIENT ERROR] Recipient identity key is required");if(null==e||""===e.trim())throw new Error("[MB CLIENT ERROR] MessageBox is required");if(null==i||"string"==typeof i&&""===i.trim())throw new Error("[MB CLIENT ERROR] Message body cannot be empty");if(await this.joinRoom(e,this.originator),null==this.socket||!this.socket.connected){Us("[MB CLIENT WARNING] WebSocket not connected, falling back to HTTP");const r=a??await this.resolveHostForRecipient(t);return await this.sendMessage({recipient:t,messageBox:e,body:i},r)}let o;try{const e=await this.walletClient.createHmac({data:Array.from((new TextEncoder).encode(JSON.stringify(i))),protocolID:[1,"messagebox"],keyID:"1",counterparty:t},this.originator);o=r??Array.from(e.hmac).map((t=>t.toString(16).padStart(2,"0"))).join("")}catch(t){throw Ks("[MB CLIENT ERROR] Failed to generate HMAC:",t),new Error("Failed to generate message identifier.")}const c=`${t}-${e}`;let h;if(qs(`[MB CLIENT] Sending WebSocket message to room: ${c}`),!0===s)h="string"==typeof i?i:JSON.stringify(i);else{const e=await this.walletClient.encrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t,plaintext:Ct("string"==typeof i?i:JSON.stringify(i),"utf8")},this.originator);h=JSON.stringify({encryptedMessage:Dt(e.ciphertext)})}return await new Promise(((r,a)=>{const d=`sendMessageAck-${c}`;let u=!1;const l=c=>{if(u)return;u=!0;const h=this.socket;if("function"==typeof h?.off&&h.off(d,l),qs("[MB CLIENT] Received WebSocket acknowledgment:",c),null==c||"success"!==c.status){Us("[MB CLIENT] WebSocket message failed or returned unexpected response. Falling back to HTTP.");const c={recipient:t,messageBox:e,body:i,messageId:o,skipEncryption:s,checkPermissions:n};this.resolveHostForRecipient(t).then((async t=>await this.sendMessage(c,t))).then(r).catch(a)}else qs("[MB CLIENT] Message sent successfully via WebSocket:",c),r(c)};this.socket?.on(d,l),this.socket?.emit("sendMessage",{roomId:c,message:{messageId:o,recipient:t,body:h}}),setTimeout((()=>{if(!u){u=!0;const c=this.socket;"function"==typeof c?.off&&c.off(d,l),Us("[CLIENT] WebSocket acknowledgment timed out, falling back to HTTP");const h={recipient:t,messageBox:e,body:i,messageId:o,skipEncryption:s,checkPermissions:n};this.resolveHostForRecipient(t).then((async t=>await this.sendMessage(h,t))).then(r).catch(a)}}),1e4)}))}async leaveRoom(t){if(await this.assertInitialized(),null==this.socket)return void Us("[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}`;qs(`[MB CLIENT] Leaving WebSocket room: ${e}`),this.socket.emit("leaveRoom",e),this.joinedRooms.delete(e)}async disconnectWebSocket(){await this.assertInitialized(),null!=this.socket?(qs("[MB CLIENT] Closing WebSocket connection..."),this.socket.disconnect(),this.socket=void 0):qs("[MB CLIENT] No active WebSocket connection to close.")}async sendMessage(t,e){if(await this.assertInitialized(),null==t.recipient||""===t.recipient.trim())throw new Error("You must provide a message recipient!");if(null==t.messageBox||""===t.messageBox.trim())throw new Error("You must provide a messageBox to send this message into!");if(null==t.body||"string"==typeof t.body&&0===t.body.trim().length)throw new Error("Every message must have a body!");let i,r,s;if(!0===t.checkPermissions)try{qs("[MB CLIENT] Checking permissions and fees for message...");const r=await this.getMessageBoxQuote({recipient:t.recipient,messageBox:t.messageBox},e);if(-1===r.recipientFee)throw new Error("You have been blocked from sending messages to this recipient.");if(r.recipientFee>0||r.deliveryFee>0){const s=r.recipientFee+r.deliveryFee;s>0&&(qs(`[MB CLIENT] Creating payment of ${s} sats for message...`),i=await this.createMessagePayment(t.recipient,r,e),qs("[MB CLIENT] Payment data prepared:",i))}}catch(t){throw new Error(`Permission check failed: ${t instanceof Error?t.message:"Unknown error"}`)}try{const e=await this.walletClient.createHmac({data:Array.from((new TextEncoder).encode(JSON.stringify(t.body))),protocolID:[1,"messagebox"],keyID:"1",counterparty:t.recipient},this.originator);r=t.messageId??Array.from(e.hmac).map((t=>t.toString(16).padStart(2,"0"))).join("")}catch(t){throw Ks("[MB CLIENT ERROR] Failed to generate HMAC:",t),new Error("Failed to generate message identifier.")}if(!0===t.skipEncryption)s="string"==typeof t.body?t.body:JSON.stringify(t.body);else{const e=await this.walletClient.encrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t.recipient,plaintext:Ct("string"==typeof t.body?t.body:JSON.stringify(t.body),"utf8")},this.originator);s=JSON.stringify({encryptedMessage:Dt(e.ciphertext)})}const n={message:{...t,messageId:r,body:s},...null!=i&&{payment:i}};try{const i=e??await this.resolveHostForRecipient(t.recipient);if(qs("[MB CLIENT] Sending HTTP request to:",`${i}/sendMessage`),qs("[MB CLIENT] Request Body:",JSON.stringify(n,null,2)),null==this.myIdentityKey||""===this.myIdentityKey)try{const t=await this.walletClient.getPublicKey({identityKey:!0},this.originator);this.myIdentityKey=t.publicKey,qs(`[MB CLIENT] Fetched identity key before sending request: ${this.myIdentityKey}`)}catch(t){throw Ks("[MB CLIENT ERROR] Failed to fetch identity key:",t),new Error("Identity key retrieval failed")}const s=await this.authFetch.fetch(`${i}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(s.bodyUsed)throw new Error("[MB CLIENT ERROR] Response body has already been used!");const a=await s.json();if(qs("[MB CLIENT] Raw Response Body:",a),!s.ok)throw Ks(`[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 Ks(`[MB CLIENT ERROR] Server returned an error: ${String(a.description)}`),new Error(a.description??"Unknown error from server.");return qs("[MB CLIENT] Message successfully sent."),{...a,messageId:r}}catch(t){Ks("[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){qs("[MB CLIENT] Starting anointHost...");try{if(!t.startsWith("http"))throw new Error("Invalid host URL");const e=await this.getIdentityKey();qs("[MB CLIENT] Fields - Identity:",e,"Host:",t);const i=[Ct(e,"hex"),Ct(t,"utf8")],r=new yi(this.walletClient,this.originator);qs("Fields:",i.map((t=>Tt(t)))),qs("ProtocolID:",[1,"messagebox advertisement"]),qs("KeyID:","1"),qs("SignAs:","self"),qs("anyoneCanSpend:",!1),qs("forSelf:",!0);const s=await r.lock(i,[1,"messagebox advertisement"],"1","anyone",!0);qs("[MB CLIENT] PushDrop script:",s.toASM());const{tx:n,txid:a}=await this.walletClient.createAction({description:"Anoint host for overlay routing",outputs:[{basket:"overlay advertisements",lockingScript:s.toHex(),satoshis:1,outputDescription:"Overlay advertisement output"}],options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1}},this.originator);if(qs("[MB CLIENT] Transaction created:",a),void 0!==n){const t=new yr(["tm_messagebox"],{networkPreset:this.networkPreset}),e=await t.broadcast(Li.fromAtomicBEEF(n));if(qs("[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 Ks("[MB CLIENT ERROR] anointHost threw:",t),t}}async revokeHostAdvertisement(t){qs("[MB CLIENT] Starting revokeHost...");const e=`${t.txid}.${t.outputIndex}`;try{const{signableTransaction:i}=await this.walletClient.createAction({description:"Revoke MessageBox host advertisement",inputBEEF:t.beef,inputs:[{outpoint:e,unlockingScriptLength:73,inputDescription:"Revoking host advertisement token"}]},this.originator);if(void 0===i)throw new Error("Failed to create signable transaction.");const r=Li.fromBEEF(i.tx),s=new yi(this.walletClient,this.originator),n=await s.unlock([1,"messagebox advertisement"],"1","anyone","all",!1,t.outputIndex,t.lockingScript),a=await n.sign(r,t.outputIndex),{tx:o}=await this.walletClient.signAction({reference:i.reference,spends:{[t.outputIndex]:{unlockingScript:a.toHex()}},options:{acceptDelayedBroadcast:!1}},this.originator);if(void 0===o)throw new Error("Failed to finalize the transaction signature.");const c=new yr(["tm_messagebox"],{networkPreset:this.networkPreset}),h=await c.broadcast(Li.fromAtomicBEEF(o));if(qs("[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 Ks("[MB CLIENT ERROR] revokeHost threw:",t),t}}async listMessages({messageBox:t,host:e,acceptPayments:i}){if("boolean"!=typeof i&&(i=!0),""===t.trim())throw new Error("MessageBox cannot be empty");let r=null!=e?[e]:[];if(0===r.length){const t=await this.queryAdvertisements(await this.getIdentityKey(),void 0);r=Array.from(new Set([this.host,...t.map((t=>t.host))]))}const s=await Promise.allSettled(r.map((async e=>{try{qs(`[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 qs(`[MB CLIENT DEBUG] listMessages failed for ${e}:`,t),t}}))),n=[],a=[];for(const t of s)"fulfilled"===t.status?n.push(t.value):a.push(t.reason);if(0===n.length)throw new Error("Failed to retrieve messages from any host");const o=new Map;for(const t of n)for(const e of t)o.has(e.messageId)||o.set(e.messageId,e);if(0===o.size)return[];const c=Array.from(o.values());for(const t of c)try{const e="string"==typeof t.body?this.tryParse(t.body):t.body;let r,s=e;if(null!=e&&"object"==typeof e&&"message"in e){const t=e.message;s="string"==typeof t?this.tryParse(t):t,r=e.payment}if(i&&null!=r?.tx&&null!=r.outputs)try{qs(`[MB CLIENT] Processing recipient payment in message from ${String(t.sender)}…`);const e=r.outputs.filter((t=>"wallet payment"===t.protocol));e.length>0?(qs(`[MB CLIENT] Internalizing ${e.length} recipient payment output(s)…`),(await this.walletClient.internalizeAction({tx:r.tx,outputs:e,description:r.description??"MessageBox recipient payment"},this.originator)).accepted?qs("[MB CLIENT] Successfully internalized recipient payment"):Us("[MB CLIENT] Recipient payment internalization was not accepted")):qs("[MB CLIENT] No wallet payment outputs found in payment data")}catch(t){Ks("[MB CLIENT ERROR] Failed to internalize recipient payment:",t)}if(null!=s&&"object"==typeof s&&"string"==typeof s.encryptedMessage){qs(`[MB CLIENT] Decrypting message from ${String(t.sender)}…`);const e=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t.sender,ciphertext:Ct(s.encryptedMessage,"base64")},this.originator),i=Lt(e.plaintext);t.body=this.tryParse(i)}else t.body=s??e}catch(e){Ks("[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 listMessagesLite({messageBox:t,host:e}){const i=await this.authFetch.fetch(`${e}/listMessages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageBox:t})}),r=await i.json();if("error"===r.status)throw new Error(r.description??"Unknown server error");const s=r.messages,n=t=>{try{return JSON.parse(t)}catch{return t}};for(const t of s)try{const e="string"==typeof t.body?n(t.body):t.body;let i=e;if(null!=e&&"object"==typeof e&&"message"in e){const t=e.message;i="string"==typeof t?n(t):t}if(null!=i&&"object"==typeof i&&"string"==typeof i.encryptedMessage){const e=await this.walletClient.decrypt({protocolID:[1,"messagebox"],keyID:"1",counterparty:t.sender,ciphertext:Ct(i.encryptedMessage,"base64")}),r=Lt(e.plaintext);t.body=n(r)}else t.body=i??e}catch(e){Ks("[MB CLIENT ERROR] Failed to parse or decrypt message in list:",e),t.body="[Error: Failed to decrypt or parse message]"}return s}tryParse(t){try{return JSON.parse(t)}catch{return t}}async acknowledgeNotification(t){await this.acknowledgeMessage({messageIds:[t.messageId]});const e="string"==typeof t.body?this.tryParse(t.body):t.body;let i;if(null!=e&&"object"==typeof e&&"message"in e&&(i=e.payment),null!=i?.tx&&null!=i.outputs)try{qs(`[MB CLIENT] Processing recipient payment in message from ${String(t.sender)}…`);const e=i.outputs.filter((t=>"wallet payment"===t.protocol));return e.length<1?(qs("[MB CLIENT] No wallet payment outputs found in payment data"),!1):(qs(`[MB CLIENT] Internalizing ${e.length} recipient payment output(s)…`),(await this.walletClient.internalizeAction({tx:i.tx,outputs:e,description:i.description??"MessageBox recipient payment"})).accepted?(qs("[MB CLIENT] Successfully internalized recipient payment"),!0):(Us("[MB CLIENT] Recipient payment internalization was not accepted"),!1))}catch(t){return Ks("[MB CLIENT ERROR] Failed to internalize recipient payment:",t),!1}return!1}async acknowledgeMessage({messageIds:t,host:e}){if(!Array.isArray(t)||0===t.length)throw new Error("Message IDs array cannot be empty");qs(`[MB CLIENT] Acknowledging messages ${JSON.stringify(t)}…`);let i=null!=e?[e]:[];if(0===i.length){const t=await this.getIdentityKey(),e=await this.queryAdvertisements(t,void 0);i=Array.from(new Set([this.host,...e.map((t=>t.host))]))}const r=await Promise.allSettled(i.map((async e=>{try{const i=await this.authFetch.fetch(`${e}/acknowledgeMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageIds:t})});if(!i.ok)throw new Error(`HTTP ${i.status}`);const r=await i.json();if("error"===r.status)throw new Error(r.description);return qs(`[MB CLIENT] Acknowledged on ${e}`),r.status}catch(t){return Us(`[MB CLIENT WARN] acknowledgeMessage failed for ${e}:`,t),null}}))),s=r.filter((t=>"fulfilled"===t.status)),n=s.find((t=>null!=t.value))?.value;if(null!=n)return n;const a=[];for(const t of r)"rejected"===t.status&&a.push(t.reason);throw new Error(`Failed to acknowledge messages on all hosts: ${a.map((t=>String(t))).join("; ")}`)}async setMessageBoxPermission(t,e){const i=e??this.host;qs("[MB CLIENT] Setting messageBox permission...");const r=await this.authFetch.fetch(`${i}/permissions/set`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageBox:t.messageBox,recipientFee:t.recipientFee,...null!=t.sender&&{sender:t.sender}})});if(!r.ok){const t=await r.json().catch((()=>({})));throw new Error(`Failed to set permission: HTTP ${r.status} - ${""!==String(t.description)?String(t.description):r.statusText}`)}const{status:s,description:n}=await r.json();if("error"===s)throw new Error(n??"Failed to set permission")}async getMessageBoxPermission(t,e){const i=e??await this.resolveHostForRecipient(t.recipient),r=new URLSearchParams({recipient:t.recipient,messageBox:t.messageBox,...null!=t.sender&&{sender:t.sender}});qs("[MB CLIENT] Getting messageBox permission...");const s=await this.authFetch.fetch(`${i}/permissions/get?${r.toString()}`,{method:"GET"});if(!s.ok){const t=await s.json().catch((()=>({})));throw new Error(`Failed to get permission: HTTP ${s.status} - ${""!==String(t.description)?String(t.description):s.statusText}`)}const n=await s.json();if("error"===n.status)throw new Error(n.description??"Failed to get permission");return n.permission}async getMessageBoxQuote(t,e){const i=e??await this.resolveHostForRecipient(t.recipient),r=new URLSearchParams({recipient:t.recipient,messageBox:t.messageBox});qs("[MB CLIENT] Getting messageBox quote...");const s=await this.authFetch.fetch(`${i}/permissions/quote?${r.toString()}`,{method:"GET"});if(!s.ok){const t=await s.json().catch((()=>({})));throw new Error(`Failed to get quote: HTTP ${s.status} - ${String(t.description)??s.statusText}`)}const{status:n,description:a,quote:o}=await s.json();if("error"===n)throw new Error(a??"Failed to get quote");const c=s.headers.get("x-bsv-auth-identity-key");if(null==c)throw new Error("Failed to get quote: Delivery agent did not provide their identity key");return{recipientFee:o.recipientFee,deliveryFee:o.deliveryFee,deliveryAgentIdentityKey:c}}async listMessageBoxPermissions(t,e){const i=e??this.host,r=new URLSearchParams;null!=t?.messageBox&&r.set("message_box",t.messageBox),void 0!==t?.limit&&r.set("limit",t.limit.toString()),void 0!==t?.offset&&r.set("offset",t.offset.toString()),qs("[MB CLIENT] Listing messageBox permissions with params:",r.toString());const s=await this.authFetch.fetch(`${i}/permissions/list?${r.toString()}`,{method:"GET"});if(!s.ok){const t=await s.json().catch((()=>({})));throw new Error(`Failed to list permissions: HTTP ${s.status} - ${""!==String(t.description)?String(t.description):s.statusText}`)}const n=await s.json();if("error"===n.status)throw new Error(n.description??"Failed to list permissions");return n.permissions.map((t=>({sender:t.sender,messageBox:t.message_box,recipientFee:t.recipient_fee,status:$s.getStatusFromFee(t.recipient_fee),createdAt:t.created_at,updatedAt:t.updated_at})))}async allowNotificationsFromPeer(t,e=0,i){await this.setMessageBoxPermission({messageBox:"notifications",sender:t,recipientFee:e},i)}async denyNotificationsFromPeer(t,e){await this.setMessageBoxPermission({messageBox:"notifications",sender:t,recipientFee:-1},e)}async checkPeerNotificationStatus(t,e){const i=await this.getIdentityKey();return await this.getMessageBoxPermission({recipient:i,messageBox:"notifications",sender:t},e)}async listPeerNotifications(t){return await this.listMessageBoxPermissions({messageBox:"notifications"},t)}async sendNotification(t,e,i){return await this.assertInitialized(),await this.sendMessage({recipient:t,messageBox:"notifications",body:e,checkPermissions:!0},i)}async registerDevice(t,e){if(null==t.fcmToken||""===t.fcmToken.trim())throw new Error("fcmToken is required and must be a non-empty string");if(null!=t.platform&&!["ios","android","web"].includes(t.platform))throw new Error("platform must be one of: ios, android, web");const i=e??this.host;qs("[MB CLIENT] Registering device for FCM notifications...");const r=await this.authFetch.fetch(`${i}/registerDevice`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fcmToken:t.fcmToken.trim(),deviceId:t.deviceId?.trim()??void 0,platform:t.platform??void 0})});if(!r.ok){const t=await r.json().catch((()=>({}))),e=String(t.description)??r.statusText;throw new Error(`Failed to register device: HTTP ${r.status} - ${e}`)}const s=await r.json();if("error"===s.status)throw new Error(s.description??"Failed to register device");return qs("[MB CLIENT] Device registered successfully"),{status:s.status,message:s.message,deviceId:s.deviceId}}async listRegisteredDevices(t){const e=t??this.host;qs("[MB CLIENT] Listing registered devices...");const i=await this.authFetch.fetch(`${e}/devices`,{method:"GET"});if(!i.ok){const t=await i.json().catch((()=>({}))),e=String(t.description)??i.statusText;throw new Error(`Failed to list devices: HTTP ${i.status} - ${e}`)}const r=await i.json();if("error"===r.status)throw new Error(r.description??"Failed to list devices");return qs(`[MB CLIENT] Found ${r.devices.length} registered devices`),r.devices}static getStatusFromFee(t){return-1===t?"blocked":0===t?"always_allow":"payment_required"}async createMessagePayment(t,e,i="MessageBox delivery payment"){if(e.recipientFee<=0&&e.deliveryFee<=0)throw new Error("No payment required");qs(`[MB CLIENT] Creating payment transaction for ${e.recipientFee} sats (delivery: ${e.deliveryFee}, recipient: ${e.recipientFee})`);const r=[],s=[],n=await this.getIdentityKey();let a=0;if(e.deliveryFee>0){const t=Dt(xe(32)),i=Dt(xe(32)),{publicKey:o}=await this.walletClient.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${t} ${i}`,counterparty:e.deliveryAgentIdentityKey},this.originator),c=(new bi).lock(_e.fromString(o).toAddress()).toHex();s.push({satoshis:e.deliveryFee,lockingScript:c,outputDescription:"MessageBox server delivery fee",customInstructions:JSON.stringify({derivationPrefix:t,derivationSuffix:i,recipientIdentityKey:e.deliveryAgentIdentityKey})}),r.push({outputIndex:a++,protocol:"wallet payment",paymentRemittance:{derivationPrefix:t,derivationSuffix:i,senderIdentityKey:n}})}if(e.recipientFee>0){const i=Dt(xe(32)),n=Dt(xe(32)),o=new Fi("anyone"),{publicKey:c}=await o.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${i} ${n}`,counterparty:t});if(null==c||""===c.trim())throw new Error("Failed to derive recipient's public key");const h=(new bi).lock(_e.fromString(c).toAddress()).toHex();s.push({satoshis:e.recipientFee,lockingScript:h,outputDescription:"Recipient message fee",customInstructions:JSON.stringify({derivationPrefix:i,derivationSuffix:n,recipientIdentityKey:t})}),r.push({outputIndex:a++,protocol:"wallet payment",paymentRemittance:{derivationPrefix:i,derivationSuffix:n,senderIdentityKey:(await o.getPublicKey({identityKey:!0})).publicKey}})}const{tx:o}=await this.walletClient.createAction({description:i,outputs:s,options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1}},this.originator);if(null==o)throw new Error("Failed to create payment transaction");return{tx:o,outputs:r,description:i}}}function js(t){try{return"string"==typeof t?JSON.parse(t):t}catch(e){return Ks("[PP CLIENT] Failed to parse input in safeParse:",t),{}}}const zs="payment_inbox";class Ws extends $s{peerPayWalletClient;_authFetchInstance;messageBox;constructor(t){const{messageBoxHost:e="https://messagebox.babbage.systems",walletClient:i,enableLogging:r=!1,originator:s}=t;super({host:e,walletClient:i,enableLogging:r,originator:s}),this.messageBox=t.messageBox??zs,this.peerPayWalletClient=i,this.originator=s}get authFetchInstance(){return null!==this._authFetchInstance&&void 0!==this._authFetchInstance||(this._authFetchInstance=new hr(this.peerPayWalletClient,void 0,void 0,this.originator)),this._authFetchInstance}async createPaymentToken(t){if(t.amount<=0)throw new Error("Invalid payment details: recipient and valid amount are required");const e=await ir(this.peerPayWalletClient),i=await ir(this.peerPayWalletClient);qs(`[PP CLIENT] Derivation Prefix: ${e}`),qs(`[PP CLIENT] Derivation Suffix: ${i}`);const{publicKey:r}=await this.peerPayWalletClient.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${e} ${i}`,counterparty:t.recipient},this.originator);if(qs(`[PP CLIENT] Derived Public Key: ${r}`),null==r||""===r.trim())throw new Error("Failed to derive recipient’s public key");const s=(new bi).lock(_e.fromString(r).toAddress()).toHex();qs(`[PP CLIENT] Locking Script: ${s}`);const n=await this.peerPayWalletClient.createAction({description:"PeerPay payment",labels:["peerpay"],outputs:[{satoshis:t.amount,lockingScript:s,customInstructions:JSON.stringify({derivationPrefix:e,derivationSuffix:i,payee:t.recipient}),outputDescription:"Payment for PeerPay transaction"}],options:{randomizeOutputs:!1}},this.originator);if(void 0===n.tx)throw new Error("Transaction creation failed!");return qs("[PP CLIENT] Payment Action:",n),{customInstructions:{derivationPrefix:e,derivationSuffix:i},transaction:n.tx,amount:t.amount}}async sendPayment(t,e){if(null==t.recipient||""===t.recipient.trim()||t.amount<=0)throw new Error("Invalid payment details: recipient and valid amount are required");const i=await this.createPaymentToken(t);await this.sendMessage({recipient:t.recipient,messageBox:this.messageBox,body:JSON.stringify(i)},e)}async sendLivePayment(t,e){const i=await this.createPaymentToken(t);try{await this.sendLiveMessage({recipient:t.recipient,messageBox:this.messageBox,body:JSON.stringify(i)},e)}catch(r){Us("[PP CLIENT] sendLiveMessage failed, falling back to HTTP:",r),await this.sendMessage({recipient:t.recipient,messageBox:this.messageBox,body:JSON.stringify(i)},e)}}async listenForLivePayments({onPayment:t,overrideHost:e}){await this.listenForLiveMessages({messageBox:this.messageBox,overrideHost:e,onMessage:e=>{qs("[MB CLIENT] Received Live Payment:",e);const i={messageId:e.messageId,sender:e.sender,token:js(e.body)};qs("[PP CLIENT] Converted PeerMessage to IncomingPayment:",i),t(i)}})}async acceptPayment(t){try{qs(`[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"}],labels:["peerpay"],description:"PeerPay Payment"},this.originator);return qs(`[PP CLIENT] Payment internalized successfully: ${JSON.stringify(e,null,2)}`),qs(`[PP CLIENT] Acknowledging payment with messageId: ${t.messageId}`),await this.acknowledgeMessage({messageIds:[t.messageId]}),{payment:t,paymentResult:e}}catch(t){return Ks(`[PP CLIENT] Error accepting payment: ${String(t)}`),"Unable to receive payment!"}}async rejectPayment(t){if(qs(`[PP CLIENT] Rejecting payment: ${JSON.stringify(t,null,2)}`),t.token.amount-1e3<1e3){qs("[PP CLIENT] Payment amount too small after fee, just acknowledging.");try{qs(`[PP CLIENT] Attempting to acknowledge message ${t.messageId}...`),null!==this.authFetch&&void 0!==this.authFetch||Us("[PP CLIENT] Warning: authFetch is undefined! Ensure PeerPayClient is initialized correctly."),qs("[PP CLIENT] authFetch instance:",this.authFetch),qs(`[PP CLIENT] Acknowledgment response: ${await this.acknowledgeMessage({messageIds:[t.messageId]})}`)}catch(t){if(null==t||"object"!=typeof t||!("message"in t)||"string"!=typeof t.message||!t.message.includes("401"))throw Ks(`[PP CLIENT] Error acknowledging message: ${t.message}`),t;Us(`[PP CLIENT] Authentication issue while acknowledging: ${t.message}`)}}else{qs("[PP CLIENT] Accepting payment before refunding..."),await this.acceptPayment(t),qs(`[PP CLIENT] Sending refund of ${t.token.amount-1e3} to ${t.sender}...`),await this.sendPayment({recipient:t.sender,amount:t.token.amount-1e3}),qs("[PP CLIENT] Payment successfully rejected and refunded.");try{qs(`[PP CLIENT] Acknowledging message ${t.messageId} after refunding...`),await this.acknowledgeMessage({messageIds:[t.messageId]}),qs("[PP CLIENT] Acknowledgment after refund successful.")}catch(t){Ks(`[PP CLIENT] Error acknowledging message after refund: ${t.message}`)}}}async listIncomingPayments(t){return(await this.listMessages({messageBox:this.messageBox,host:t})).map((t=>{const e=js(t.body);return{messageId:t.messageId,sender:t.sender,token:e}}))}}return e})()));